Junior — Middle
What is the difference between the 'forEach' and 'map' methods when processing arrays in JavaScript?
sobes.tech AI
Answer from AI
In JavaScript, the methods forEach and map are used for array traversal but serve different purposes and behaviors:
-
forEachexecutes a function for each element of the array but does not return a new array. It is used for side effects, such as logging to the console or modifying external variables. -
mapapplies a function to each element and returns a new array consisting of the results of that function. It is used for transforming arrays.
Example:
const numbers = [1, 2, 3];
// forEach
numbers.forEach(num => console.log(num * 2)); // Will output 2, 4, 6, but will not create a new array
// map
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
Key difference: map returns a new array with the results, forEach does not.