Difference Between forEach() and map() in JavaScript Array
Array.forEach() and Array.map()
In this tutorial, we’ll see the difference between Array.forEach()
and Array.map()
methods in JavaScript Array.
The forEach()
and map()
method are mostly used to iterate through an Array elements but there are few differences, We’ll look at them one by one.
Returned Value
The forEach()
method returns undefined whereas map()
returns a new array with transformed elements.
Let’s find out the square of each element in an Array using these two methods:
const numbers = [1, 2, 3, 4, 5];
// using forEach()
const squareUsingForEach = [];
numbers.forEach(x => squareUsingForEach.push(x*x));
// using map()
const squareUsingMap = numbers.map(x => x*x);
console.log(squareUsingForEach); // [1, 4, 9, 16, 25]
console.log(squareUsingMap); // [1, 4, 9, 16, 25]
Since forEach()
returns undefined, we need to pass an empty array to create a new transformed array. There is no such issue with map()
method which returns the new transformed array directly. It is recommended to use map()
method in such cases.
Chaining other methods
The map()
method output can be chained with other methods such as reduce()
, sort()
, filter()
to perform multiple operations in a single statement.
On the other hand, forEach()
is a terminal method means it cannot be chained with other methods since it returns undefined.
Let’s find out the sum of square of each element in an Array using these two methods:
const numbers = [1, 2, 3, 4, 5];
// using forEach()
const squareUsingForEach = []
let sumOfSquareUsingForEach = 0;
numbers.forEach(x => squareUsingForEach.push(x*x));
squareUsingForEach.forEach(square => sumOfSquareUsingForEach += square);
// using map()
const sumOfSquareUsingMap = numbers.map(x => x*x).reduce((total, value) => total + value);
console.log(sumOfSquareUsingForEach); // 55
console.log(sumOfSquareUsingMap); // 55
It is such a tedious job to use forEach()
method when multiple operations are required. We can use map()
method in such cases.
Performance
We have created an array with 1 million random numbers (ranging from 1 to 1000). Let’s check the performance of each method.
// Array:
var numbers = [];
for ( var i = 0; i < 1000000; i++ ) {
numbers.push(Math.floor((Math.random() * 1000) + 1));
}
// 1. forEach()
console.time("forEach");
const squareUsingForEach = [];
numbers.forEach(x => squareUsingForEach.push(x*x));
console.timeEnd("forEach");
// 2. map()
console.time("map");
const squareUsingMap = numbers.map(x => x*x);
console.timeEnd("map");
Here is the result after running the above code on MacBook Pro’s Google Chrome v83.0.4103.106 (64-bit). I suggest to copy the above code and try yourself in console.
forEach: 26.596923828125ms
map: 21.97998046875ms
Clearly map()
method performs better then forEach()
for transforming elements.
Break the iteration
This is not the difference between these two methods but important to know that there is no way to stop or break;
the iteration if you are using forEach()
or map()
methods. The only way is to throw an exception from the callback function which may not be desired in most of the cases.
If we use break;
statement within the callback function of forEach()
or map()
method,
const numbers = [1, 2, 3, 4, 5];
// break; inside forEach()
const squareUsingForEach = [];
numbers.forEach(x => {
if(x == 3) break; // <- SyntaxError
squareUsingForEach.push(x*x);
});
// break; inside map()
const squareUsingMap = numbers.map(x => {
if(x == 3) break; // <- SyntaxError
return x*x;
});
JavaScript throws SyntaxError as follows:
ⓧ Uncaught SyntaxError: Illegal break statement
If you need such behavior then you should use simple for
loop or for-of
/ for-in
loop.
const numbers = [1, 2, 3, 4, 5];
// break; inside for-of loop
const squareUsingForEach = [];
for(x of numbers){
if(x == 3) break;
squareUsingForEach.push(x*x);
};
console.log(squareUsingForEach); // [1, 4]
Final Thoughts
It is recommended to use map()
to transform elements of an array since it is having short syntax, it’s chainable and has better performance.
You shouldn’t use map()
if you’re not using returned array or not transforming elements of an array. It’s an anti-pattern; instead you should use forEach()
method.
At last, if you want to stop or break the iteration of an array based on some condition then you should use simple for
loop or for-of
/ for-in
loop.