Introduction
If you are a Javascript Developer, you probably use map()
and forEach()
method, but do you really know the difference between both of them ?
We will see how they works and in which case it is useful to use them.
map()
The map()
method is used when you want to create a new array and modify elements in it. A new array will be returned with his new values (or not).
Exemple :
const array = [1, 2, 3, 4, 5];
const newArray = array.map(item => item * 5);
console.log(array);
//Output : [1, 2, 3, 4, 5];
console.log(newArray);
//Output : [5, 10, 15, 20, 25];
Here, in this example we can see that we have array
which has not changed, and the newArray
which contains the new array with the new values.
We can also attach an other method after map()
.
Exemple :
const array = [1, 2, 3, 4, 5];
const newArray = array.map(item => item * 5).sort((a, b) => b - a);
console.log(newArray);
//Output : [25, 20, 15, 10, 5];
forEach()
The forEach()
method is used when you want edit an element in an existing array. But unlike map()
, forEach()
do not return a new array.
Exemple :
const array = [1, 2, 3, 4, 5];
const newArray = array.forEach((item, index, arr) => arr[index] = item * 5);
console.log(array);
//Output : [5, 10, 15, 20, 25];
console.log(newArray);
//Output : undefined;
Here, array
contain the new values, and newArray
is undefined because forEach
do not return an array like map()
.
Conclusion
So, the main diffenrence between both of them is that map()
method return a new array with the new values and we can attach another method to it, while forEach() return nothing and we cannot attach any other method to it.
Top comments (0)