Map vs forEach in JavaScript

Map vs forEach in JavaScript

Ferenc Almasi β€’ 2020 November 12 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

Both of them iterate through the elements of an array. The difference here is that map creates a new array while forEach doesn’t. If you follow the functional programming paradigm and you want to keep data immutable then you should use map. If you want to mutate the elements of the original array, you should use forEach. Take the following example:

Copied to clipboard! Playground
const animals = [...];

// Mutate the elements of the original array
animals.forEach((animal, index) => animals[index] = `${animal} πŸ–οΈ`);

// Creates a new array
const newAnimals = animals.map(animal => `${animal} πŸ–οΈ`);
map-vs-foreach.js

When using forEach, the animals array will also be changed. This is not the case for map. It will create an entire new array. To reiterate:

  • The callback of forEach mutates the original items in the array
  • map returns a transformed array while keeping the original intact

Note that forEach itself does not mutate the array. However, the callback that you pass to it may do if you choose to.

The difference between map vs forEach in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Why Do You Need to Know About Functional Programming?

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.