In this article, I’ll compare the JavaScript array functions forEach
and map
. After reading this, you should know when to use which function and why.
The map
function iterates over a given array.
The value you return in the function will replace the value in the original array.
const array = [1, 2, 3];
array.map((item) => {
return item * 2; // changes the original array
});
console.log(array);
[2, 4, 6]
Changing the original array without re-assigning is called object mutation.
If you don’t want to change the original array, you can copy it by using the spread operator:
// Makes a copy of the array
const result = [...array];
result.map((item) => {
return item * 2;
});
This function allows you to iterate over an array without mutating the original one.
const array = [1, 2, 3];
array.forEach((item) => {
item * 2; // effectively, this operation does nothing
});
console.log(array);
[1, 2, 3]
As you can see from the outputs, the use-cases for these two functions are totally different.
You will use map
for changing each value of a given array, while forEach
simplifies iterating over an array without changing its values.
#javascript #programming #developer #web-development