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);
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]
Explanation:
Key Differences:
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!