Here’s the difference between map() and forEach() in JavaScript:
🔹 forEach()
- Purpose: Executes a function on each array element.
- Return: Returns
undefined. - Use Case: Use when you only want side effects (e.g., logging, updating DOM).
const arr = [1, 2, 3];
arr.forEach(num => console.log(num * 2)); // prints 2, 4, 6
🔹 map()
- Purpose: Transforms each element and returns a new array.
- Return: Returns a new array with modified values.
- Use Case: Use when you need a transformed array.
const arr = [1, 2, 3];
const doubled = arr.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
🔁 Summary:
- Use
map()when you need a new array with modified data. - Use
forEach()when you just want to perform actions on each element without returning anything.