The difference between forEach and map in js

forEach and map are both JavaScript methods for traversing an array, but they do different things.

The forEach method is used to iterate over each element in the array and execute a callback function for each element. This callback function can accept three parameters: the value of the current element, the index of the current element, and the entire array. The forEach method does not return any value, it just executes the callback function for each element.

The map method is also used to traverse each element in the array, but it will return a new array that contains the return value after executing the callback function for each element in the original array. This callback function can also accept three parameters: the value of the current element, the index of the current element, and the entire array.

So, the main difference between forEach and map is their return values. forEach returns no value, while map returns a new array. Here is an example to better illustrate the difference between them:

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

// 使用 forEach 方法
numbers.forEach((number) => {
  console.log(number * 2);
});

// 使用 map 方法
const doubledNumbers = numbers.map((number) => {
  return number * 2;
});

console.log(doubledNumbers);

In the above code, we first define an array containing numbers. Then, we use the forEach method to iterate over each element in the array and execute a callback function on each element, this callback function multiplies each element by 2 and prints the result to the console. Since the forEach method does not return any value, we cannot use it to create a new array.

Next, we use the map method to iterate over each element in the array and execute a callback function on each element, this callback function multiplies each element by 2 and returns the result. Since the map method returns a new array, we can store its result in a variable and print it to the console.

So, the main difference between forEach and map is their return values. forEach returns no value, while map returns a new array.

Guess you like

Origin blog.csdn.net/qq_46103732/article/details/130698516
Recommended