DEV Community

Cover image for JavaScript map vs. forEach
Farhana Binte Hasan
Farhana Binte Hasan

Posted on

JavaScript map vs. forEach

.forEach()

What is it?

This method is the most similar to the forloop. Example -

// forloop
const numbers = [2,6,8,10,12];

for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode
// forEach
const numbers = [2,6,8,10,12];

numbers.forEach(number => {
    console.log(number);
});
Enter fullscreen mode Exit fullscreen mode

forEach() is simply executed "for each" element of the array.

.map()

What is it?

map is almost similar to the forEach method. This method loops through each element.

// map
const numbers = [2,6,8,10,12];

numbers.map(number =>console.log(number))
Enter fullscreen mode Exit fullscreen mode
// map
const numbers = [2,6,8,10,12];

numbers.map(number =>console.log(number * 2))
Enter fullscreen mode Exit fullscreen mode

map vs. forEach:

forEach:

It calls a function for each element of an array but doesn't return anything. That means no result fount means undefined

const numbers = [2,6,8,10,12];

let result = numbers.forEach((number) =>{
    return number*10
})
console.log(result); //undefined
Enter fullscreen mode Exit fullscreen mode

map:

This method returns a new array by applying the callback function on each element of an array.

// map
const numbers = [2,6,8,10,12];

let result = numbers.map((number) =>{
    return number*10
})
console.log(result); //[20,60,80,100,120] 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)