DEV Community

Avinash Maurya
Avinash Maurya

Posted on

Differences between forEach and map in JavaScript

The primary differences between forEach and map in JavaScript (often used with arrays) lie in their return values and purposes:

forEach

  • Purpose: Iterates over each element in an array, allowing you to perform an action on each element.
  • Return value: undefined.
  • Use cases:
    • Modifying elements in-place (be cautious of potential side effects).
    • Performing side effects like logging or DOM manipulation for each element.

Example:

const numbers = [1, 2, 3];
numbers.forEach(number => console.log(number * 2)); // Output: 2, 4, 6 (no new array)
Enter fullscreen mode Exit fullscreen mode

map

  • Purpose: Creates a new array with the results of applying a callback function to each element in the original array.
  • Return value: A new array containing the transformed elements.
  • Use cases:
    • Transforming elements (e.g., doubling values, converting to uppercase).
    • Creating a new array based on a calculation or manipulation of the original elements.

Example:

const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6] (new array)
Enter fullscreen mode Exit fullscreen mode

Key Differences:

Feature forEach map
Return Value undefined (doesn't create a new array) A new array containing transformed elements
Purpose Iterates and performs actions on existing elements Transforms elements and creates a new array
Side Effects Can be used for in-place modifications (potentially risky) Usually doesn't have side effects (creates a new array)
Common Use Cases Modifying elements, side effects (logging, DOM) Transforming elements, creating a new array based on logic

Choosing the Right Method:

  • Use forEach if you want to iterate through elements and perform side effects without creating a new array.
  • Use map if you want to create a new array with transformed elements based on a callback function.

Top comments (0)