map() vs forEach() in JavaScript

Introduction

In this tutorial, you will learn the concept of the difference between map and forEach.

When you work with an array in JavaScript, map() and forEach() are used to iterate over its elements.

map() and forEach() are work differently.

What is map() in JavaScript?

The map() method is used to create a new array by applying a function to every element of an existing array.

Example


 const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled);

Output:

[2, 4, 6, 8, 10]

Important Notes:

  1. It is used to return a new array.
  2. It does not modify the original array.
  3. It is commonly used for data transformation.

What is forEach() in JavaScript?

The forEach() method executes a function for each element in an array but does not return a new array.

Example


const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
  console.log(num * 2);
});

Output:

2
4
6
8
10

Important Notes:

  1.  It does not return a new array.
  2. It is used for side effects like logging, DOM updates, or API calls.
  3. It returns undefined.

Key Differences Between map() and forEach()

Feature map() forEach()
Return Value Returns a new array Returns undefined
Purpose Transform array data Execute operations
Chainable Yes No
Modification Does not modify original array Usually used to modify or perform actions
Functional Programming Preferred Less commonly used

When to use the map() method?

You can use the map() method

  1. If you need to transform data.
  2. If you want to create a new array.
  3. If you want method chaining.

Example:


const prices = [100, 200, 300];
const discounted = prices.map(price => price * 5);

When to use the forEach() method?

You can use the forEach() method when

  1.  If you only want to perform an action.
  2.  If you don’t need a new array.
  3. If you want to log or update data.

Example:


const users = ["John", "Rom", "Tom"];
users.forEach(user => {
  console.log("Hello " + user);
});

Common Mistakes Developers Make

Many developers use forEach() when map() is needed.

Incorrect Approach


const numbers = [1,2,3];
let doubled = [];
numbers.forEach(num => {
  doubled.push(num * 2);
});

Best Approach


const numbers = [1,2,3];
const doubled = numbers.map(num => num * 2);

Real-Life Example: Applying a Discount to Product Prices

Suppose you have your own e-commerce website where you have a list of product prices, and you want to apply a 10% discount to each product.

Using forEach() Method


const prices = [100, 200, 300];
const discountedPrices = [];

prices.forEach(function(price) {
  discountedPrices.push(price * 0.9);
});

console.log(discountedPrices);

Using map() Method


const prices = [100, 200, 300];

const discountedPrices = prices.map(function(price) {
  return price * 0.9;
});

console.log(discountedPrices);

Output:

[90, 180, 270]

Explanation:

Both methods iterate over the array, but they behave differently.

forEach()

  1. Executes a function for each array element.
  2. Does not return a new array.
  3. Mainly used when performing actions like logging data or updating the DOM.

map():

  1. Creates and returns a new array with transformed values.
  2. Commonly used when you want to modify or transform array data.

Interview Questions

Q 1: What is the main difference between map() and forEach() in JavaScript?
Ans: map() returns a new array after transforming each element, while forEach() simply executes a function for each element and does not return a new array.
Q 2: Can forEach() return a value?
Ans: No, forEach() always returns undefined.
Q 3: When should you use map() instead of forEach()?
Ans: Use map() when you want to create a new array by transforming existing array elements.
Q 4: Can map() modify the original array?
Ans: No, map() does not modify the original array; it returns a new array.

Conclusion

Both map() and forEach() are used to iterate over arrays in JavaScript, but they work differently. forEach() is best suited for performing actions like logging values or executing side effects, while map() is ideal when you want to transform data and generate a new array.

In modern JavaScript development, map() is often preferred for data transformation tasks, because it keeps code cleaner and more functional.

Compare JavaScript Methods