JavaScript map vs forEach: Key Differences with Examples

The Syntax NodeThe Syntax Node
2 min read

JavaScript provides several methods for iterating over arrays, with map and forEach being two of the most commonly used. Although they might appear similar, they serve different purposes. In this blog, we'll break down their differences and provide practical JavaScript examples to help you understand when to use each.

1. What is map in JavaScript?

The map method is used to create a new array by applying a transformation function to each element in an existing array. This method does not alter the original array but instead returns a modified copy.

Syntax:

const newArray = array.map(callback(element, index, array));

Example:

const values = [2, 4, 6, 8];
const doubledValues = values.map(num => num * 2);

console.log(doubledValues); // Output: [4, 8, 12, 16]
console.log(values); // Output: [2, 4, 6, 8] (original array remains unchanged)

2. What is forEach in JavaScript?

The forEach method executes a callback function on each element of the array but does not create a new array. Instead, it is typically used to perform side effects like logging or modifying elements directly.

Syntax:

array.forEach(callback(element, index, array));

Example:

const values = [2, 4, 6, 8];
values.forEach(num => console.log(num * 2));
// Output: 4 8 12 16 (each element is logged but no new array is returned)

3. Differences Between map and forEach

FeaturemapforEach
Returns a new array?YesNo
Modifies the original array?NoNo (unless explicitly modified)

4. When to Use map vs. forEach

  • Use map when you want to apply a transformation to every element in an array and return a new array.

  • Use forEach when you need to execute a function on each array element without returning a new array.

Example Comparison:

Using map to increase values:

const numbers = [10, 20, 30, 40];
const increased = numbers.map(num => num + 5);
console.log(increased); // Output: [15, 25, 35, 45]

Using forEach to log values:

numbers.forEach(num => console.log(num + 5));
// Output: 15 25 35 45 (no new array is created)

Conclusion

Understanding the differences between map and forEach is essential for writing efficient JavaScript code. Use map when you need a transformed array, and use forEach when you need to execute a function without returning a new array.

0
Subscribe to my newsletter

Read articles from The Syntax Node directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

The Syntax Node
The Syntax Node

I am a JavaScript Full Stack Developer with expertise in front-end frameworks like React and Angular, and back-end technologies such as Node.js and Express.