Difference between forEach() and map() in JS array

Translator: front end Xiaozhi
Author: Ashish Lahoti
Source: odingconcepts

Like again, wechat search [Daqian world] focuses on this person who has no big factory background but has an upward positive attitude. This article GitHub https://github.com/qq44924588... It has been included in the, the articles have been classified, and a lot of my documents and tutorial materials have been sorted out**

27 dual 12 Alibaba servers, general purpose click here If you want to buy, you can ask me to return 30 cash, which is equal to 27 yuan. It is only for new users. You can buy it with your family's mobile phone number!

Today, let's take a look at Array Foreach() and Array The difference between map () methods.

forEach() and map() methods are usually used to traverse Array elements, but there is little difference. Let's introduce them one by one.

1. Return value

The forEach() method returns undefined, while map() returns a new array containing the converted elements.

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

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

// Use 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 converted array. There is no such problem with the map() method, which directly returns the new converted array. In this case, the map() method is recommended.

2. Link other methods

The map() method output can be linked with other methods (such as reduce(), sort(), filter()) to perform multiple operations in one statement.

On the other hand, forEach() is a terminal method, which means that it cannot be linked to other methods because it returns undefined.

We use the following two methods to find the sum of squares of each element in the array:

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

// Use 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);     // 55

When multiple operations are needed, using the forEach() method is a tedious task. We can use the map() method in this case.

3. Performance

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

This is in MacBook Pro's Google Chrome V83 The result of running the above code on 0.4103.106 (64 bit). It is recommended to copy the above code and try it in your own console.

forEach: 26.596923828125ms
map:     21.97998046875ms

Obviously, the map() method is better than the forEach() transformation element.

4. Interrupt traversal

Otherwise, both methods cannot be used to throw an exception:

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;
});

The above code will throw SyntaxError:

ⓧ Uncaught SyntaxError: Illegal break statement

If you need to break the traversal, you should use a simple for loop or a 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]

5. Finally

It is recommended to use map() to transform the elements of an array, because it has short syntax, can be linked, and better performance.

If you don't want to return an array or convert the elements of an array, use the forEach() method.

Finally, if you want to stop or interrupt the convenience of an array based on some condition, you should use a simple for loop or a for of / for in loop.

The bugs that may exist after the code is deployed cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful BUG monitoring tool Fundebug.

Original text: https://codingnconcepts.com/j...

communication

The article is continuously updated every week. You can search "Daqian world" on wechat to read and urge more for the first time (one or two articles earlier than the blog). This article GitHub https://github.com/qq449245884/xiaozhi It has been collected and sorted out many of my documents. Welcome to Star and improve it. You can refer to the examination center for review during the interview. In addition, you can pay attention to the official account. You can see the benefits by replying to the benefits in the background. You know.

Tags: Javascript Front-end html

Posted by mchip on Sat, 30 Apr 2022 14:35:30 +0300