The map() method
The map()
method loops through each element in array and calls the provided function for each element. This method creates a new array and doesn’t alter the original array.
const numbers = [5, 6, 8, 14, 32];
const updatedNumbers = numbers.map((number) => {
return number + 10;
});
console.log(updatedNumbers); // [15, 16, 18, 24, 42]
The filter() method
The filter()
method in JavaScript creates a new array with the elements that satisfies the provided condition. This method calls a provided function for each element in array and verifies the condition given in the provided function and passes only those elements that satisfy the given condition.
const numbers = [5, 6, 9, 32, 14];
const even = numbers.filter((number) => {
return number % 2 === 0;
});
console.log(even); // [6, 32, 14]
The forEach() method
forEach()
is used to execute the same code on every element in an array but does not change the array and it returns undefined.
Example:
In the example below we would use .forEach() to iterate over an array of food and log that we would want to eat each of them.
let food = ['mango','rice','pepper','pear'];
food.forEach(function(foodItem){
console.log('I want to eat '+foodItem);
});
Hope you have got a clear idea about both JavaScript array methods map()
filter()
and forEach()
.
Top comments (1)
A simple summary that helped me a lot:
map --> transform each item in an array and output to a new array without altering the original array
filter --> remove items of an array based on some criteria without altering the original array
forEach --> perform some function on each item of an array
Furthermore