Middle
What is the difference between the array methods map() and forEach()?
sobes.tech AI
Answer from AI
The map() method creates a new array by filling it with the results of calling a provided function on every element in the original array. It is used when you need to transform each element and get a new array.
The forEach() method simply executes a function for each element in 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.
Example:
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // [2, 4, 6]
numbers.forEach(n => console.log(n)); // Will output 1, 2, 3, but will not create a new array
Key difference: map() returns a new array, forEach() does not.