When to use foreach(), filter(),map() and reduce() in JavaScript?

Last Updated on :February 26, 2024

forEach() :
forEach method is one of the several ways to loop through arrays. forEach method takes a callback function and runs that callback function on each element of the array one by one.



var arr = [10, 20, 30];

arr.forEach(function (elem, index){
console.log(elem + ' comes at ' + index);
});

Output:


10 comes at 0
20 comes at 1
30 comes at 2

filter():
filter() method takes each element in an array and applies a conditional statement against it. If the value is true then the element gets pushed to the resulting array but if the return value is false then element does not get pushed to the resulting array.
Note: filter method does not update the existing array it will return a new filtered array every time.


var arr = [10, 20, 30]; 

var result = arr.filter(function(elem){
    return elem !== 20;
})
console.log(result)

Output:


 [10, 30]  

map():
map() method allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array’s elements and save them to a new array.


var arr = [10, 20, 30];

var mappedArr = arr.map(function(elem) {
    return elem * 10;
});
console.log(mappedArr);

Output:


 [100,200,300]

reduce():
reduce() method of the array object is used to reduce the array to one single value.


var arr = [10, 20, 30];

var sum = arr.reduce(function(sum, elem) {
    return sum + elem;
});
console.log(sum);

Output :


 60

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *