1. Purpose
forEach- Used to iterate over an array.
- Executes a callback for each element.
- Does not return anything useful (always
undefined).
map- Used to transform an array.
- Executes a callback for each element.
- Returns a new array with transformed values (same length as original).
2. Return Value
forEach→undefinedmap→ new array
3. Usage Example
const numbers = [1, 2, 3, 4];
// forEach example (just printing)
numbers.forEach(num => console.log(num * 2));
// Output: 2, 4, 6, 8 (but no new array)
// map example (creating new array)
const doubled = numbers.map(num => num * 2);
console.log(doubled);
// Output: [2, 4, 6, 8]
4. When to Use
- Use
forEach→ when you only need to perform a side effect (e.g., logging, updating DOM, pushing into another array). - Use
map→ when you want to create a new array based on transformations.
👉 In short:
forEach= do somethingmap= do something and get a new array
