HomeJAVASCRIPTDifference between forEach and map.

Difference between forEach and map.

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

  • forEachundefined
  • mapnew 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 something
  • map = do something and get a new array

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *