When To Use Map Vs Foreach Javascript

When To Use Map Vs Foreach Javascript

3 min read Jun 18, 2024
When To Use Map Vs Foreach Javascript

When to Use map vs. forEach in JavaScript

Both map and forEach are JavaScript array methods that iterate over array elements. But, they have different purposes and when used correctly, can significantly improve the readability and efficiency of your code.

forEach

Purpose: forEach is used to iterate over an array and perform an action on each element.

Key Features:

  • No return value: forEach does not return a new array. It's mainly used for side effects like modifying the original array or logging to the console.
  • Mutates the original array: If you modify the array elements inside the forEach callback, the original array will be mutated.

Example:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(number => {
  console.log(number * 2);
});

This code iterates over the numbers array and logs the doubled value of each number to the console.

map

Purpose: map is used to transform an array into a new array by applying a function to each element.

Key Features:

  • Returns a new array: map always returns a new array with the transformed elements.
  • Doesn't mutate the original array: The original array remains untouched.

Example:

const numbers = [1, 2, 3, 4, 5];

const doubledNumbers = numbers.map(number => number * 2);

console.log(doubledNumbers); // [2, 4, 6, 8, 10]

This code creates a new array doubledNumbers where each element is the doubled value of the corresponding element in the numbers array.

When to Use Which Method

Use forEach when:

  • You want to perform an action on each element, but you don't need to create a new array.
  • You want to modify the original array directly.

Use map when:

  • You want to transform the array elements into a new array with different values.
  • You want to preserve the original array while creating a new one.

Conclusion

Choosing between map and forEach depends on the specific task you're trying to accomplish. Understanding their differences and uses will help you write cleaner and more efficient JavaScript code.