Home > Web Front-end > JS Tutorial > What's the Key Difference Between JavaScript's `forEach()` and `map()` Methods?

What's the Key Difference Between JavaScript's `forEach()` and `map()` Methods?

Mary-Kate Olsen
Release: 2024-12-20 05:38:13
Original
437 people have browsed it

What's the Key Difference Between JavaScript's `forEach()` and `map()` Methods?

Understanding the Differences between .forEach() and .map() in JavaScript

Beyond the primary distinction that .forEach() operates on the original array while .map() creates a new array, there are nuances to consider. This is exemplified in the provided code:

function practice(i) {
  return i + 1;
}

var a = [-1, 0, 1, 2, 3, 4, 5];
var b = [0];
var c = [0];
console.log(a);
b = a.forEach(practice);
console.log("=====");
console.log(a);
console.log(b);
c = a.map(practice);
console.log("=====");
console.log(a);
console.log(c);
Copy after login

Output:

[-1, 0, 1, 2, 3, 4, 5]
=====
[-1, 0, 1, 2, 3, 4, 5]
undefined
=====
[-1, 0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
Copy after login

Explanation:

  • forEach(): This method iterates over each element in the array, but it doesn't return a value. In the example, a.forEach(practice) executes the practice function on each element in 'a', but the result (undefined) is not assigned to 'b'. Hence, 'b' remains unchanged.
  • map(): This method creates a new array by transforming each element in the original array. In the example, a.map(practice) applies the practice function to each element in 'a' and returns a new array 'c' with the transformed values.

Key Differences:

  • Return Value: forEach() doesn't return anything, while map() creates a new array.
  • Operation: forEach() iterates and performs side effects, while map() iterates and transforms.
  • Side Effects: forEach() can mutate the original array through the callback function, while map() only transforms the values.

Understanding these differences is crucial when choosing the appropriate method for array manipulation in JavaScript.

The above is the detailed content of What's the Key Difference Between JavaScript's `forEach()` and `map()` Methods?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template