“This is the 21st day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

This article explores the differences between the array.foreach () and array.map () methods of JavaScript arrays.

1. The return value

The forEach() method returns undefined and map() returns a new array containing the converted elements. Now use these two methods to get a new array made up of the squares of each element in the original array.

const numbers = [1, 2, 3, 4, 5];

// 使用 forEach()
const squareUsingForEach = [];
numbers.forEach(x => squareUsingForEach.push(x*x));

// 使用 map()
const squareUsingMap = numbers.map(x => x*x);

console.log(squareUsingForEach); // [1, 4, 9, 16, 25]
console.log(squareUsingMap);     // [1, 4, 9, 16, 25]
Copy the code

Since forEach() returns undefined, we need to pass an empty array to create a new conversion array. The map() method doesn’t have this problem; it simply returns the new transform array. The map() method is recommended in this case.

2. Chain call other methods

The output of the map() method can be chained to other methods, such as reduce(), sort(), filter(), allowing multiple operations to be performed in a single statement.

On the other hand, forEach() is a terminal method, which means it can’t chain-call other methods because it returns undefined. Here we get the sum of the squares of each element in the array using these two methods:

const numbers = [1, 2, 3, 4, 5]; ForEach () const squareUsingForEach = [] let sumOfSquareUsingForEach = 0; numbers.forEach(x => squareUsingForEach.push(x*x)); squareUsingForEach.forEach(square => sumOfSquareUsingForEach += square); // Use map() const sumOfSquareUsingMap = numbers. Map (x => x*x).reduce((total, value) => total + value); console.log(sumOfSquareUsingForEach); // 55 console.log(sumOfSquareUsingMap); / / 55Copy the code

Using the forEach() method can be tedious when multiple operations are required. In this case, we can use the map() method to be more refined.

3. The performance

Let’s create an array of 1 million random numbers ranging from 1 to 1000. Let’s examine the performance of both methods.

// 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");Copy the code

This is the result of running the above code on Google Chrome V83.0.4103.106 (64-bit) on a MacBook Pro. I suggest copying the code above and trying it out in the console.

ForEach: 26.596923828125 ms map: 21.97998046875 msCopy the code

Clearly, the map() method performs better than forEach() at transforming elements.

4. Break iteration

At this point, the two methods are no different; if you use forEach() or map(), the only way to stop iterating is to throw an exception from the callback function. If we use the break statement in the forEach() or map() callback:

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;
});
Copy the code

JavaScript throws a SyntaxError:

Modify Uncaught SyntaxError: Illegal break statementCopy the code

If you need to terminate a loop, you should use a 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]Copy the code

5. To summarize

It is recommended to use map() to convert elements of an array because it has a short syntax, can be chained, and better performance. Map () should not be used if you do not need to return an array or transform array elements. The forEach() method should be used. Finally, if you want to stop or break the iteration of an array depending on some condition, you should use a simple for loop or for-of/for-in loop.

The front end is beautiful