DEV Community

Hemant Govekar
Hemant Govekar

Posted on

map, foreach and reduce difference in javascript

map(), forEach(), and reduce() are array methods in JavaScript, each serving a distinct purpose.

1️⃣ map()

  • Creates a new array by transforming each element.
  • Returns a modified array without changing the original.

Example:

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

2️⃣ forEach()

  • Iterates over an array but does not return anything.
  • Used when you need to execute a function on each element (like logging data).

Example:

const numbers = [1, 2, 3, 4];
numbers.forEach(num => console.log(num * 2)); 
// Logs: 2, 4, 6, 8
Enter fullscreen mode Exit fullscreen mode

Unlike map(), there’s no new array—forEach() just loops.

3️⃣ reduce()

  • Reduces the array into a single value (sum, product, etc.).
  • Takes an accumulator and a current value to compute a result.

Example: Sum of array elements

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10
Enter fullscreen mode Exit fullscreen mode

Here, reduce() accumulates values (acc) and returns the final sum.

🚀 Key Differences

Method Purpose Returns New Array?
map() Transform each item ✅ Yes
forEach() Execute a function on each item ❌ No
reduce() Condense array into a single value ❌ No

If you're manipulating data (map()), looping for side effects (forEach()), or computing a single result (reduce()), each method has its place!

Top comments (6)

Collapse
 
nevodavid profile image
Nevo David

super helpful, tbh i always wonder if i overuse map or reduce when a simple forEach would do - you think there’s a real sweet spot for picking the right one or is it all just habit

Collapse
 
hemantgovekar profile image
Hemant Govekar

This article should be the guiding principle for your future then :-)

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

pretty cool seeing all of these finally broken down so clean - gotta ask tho, you think one of these ends up being overused just because it feels easier?

Collapse
 
hemantgovekar profile image
Hemant Govekar

Thanks Nathan , you like the article. I see map being used more often than not, but this article will make it clear when to use what.
There more youtube videos I am planning to explain most asked interview questions on my youtube channel. If you would like to subscribe? youtube.com/channel/UCajNSAb41SHFY... .

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

Done!

Thread Thread
 
hemantgovekar profile image
Hemant Govekar

Thanks Nathan !!! If you have anything which require explaination in ReactJs or Asp.net core web api. Let me know I will try to create a youtube videos.