MathsGee is free of annoying ads. We want to keep it like this. You can help with your DONATION

1 like 0 dislike
44 views
Can you describe the main difference between the Array.forEach() loop and Array.map() methods and why you would pick one versus the other?
| 44 views

0 like 0 dislike

JavaScript can be confusing sometimes. You may have come across the two popular methods Array.Prototype.map() and Array.Prototype.forEach() in your codebase. If you are unsure about their differences, keep reading. This also happens to be a popular frontend developer interview question.

Array.prototype.forEach

Anytime you want to iterate through the items in an array, the first thing that comes to our mind in any programming language is the for loop. forEach() in JavaScript is an interesting alternative to the regular for loops.

The forEach() iterates through the elements in the array. It calls a provided callback function once for each element in the array in ascending order.

The callback function accepts three arguments:

• value of the element
• index of the element
• array object

Let’s take a look at an example to see how forEach() works.

let temp = [1, 4, 9];
temp.forEach((item, index) => {
return temp[index] = item * 3;
});

// temp is now [3, 12, 27]

Array.prototype.map

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map() calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

The callback accepts three arguments:

• value of the element
• index of the element
• array object

You may have used the map() function before. It qualifies as a higher-order function, because it takes in a callback function as an input argument.

let numbers = [1, 4, 9];
let triples = numbers.map((item) => {
return item * 3;
});

// numbers is still [1, 4, 9]
// triples is [3, 12, 27]

In the example above, we have an array of numbers and creating a new array using the map(). The map() takes a function as an argument. The argument item within the function will automatically be assigned from each element of the array as map() loops through the original array.

What is the difference?

If you notice closely, although they look very similar there is a fundamental difference between forEach() and map() functions.

forEach() changes the original array, whereas map() returns a new array, without mutating the original array.

by Diamond (50,571 points)

0 like 0 dislike
1 like 0 dislike
0 like 0 dislike
1 like 0 dislike