![Map vs forEach in JavaScript](https://allma.si/blog/wp-content/uploads/2020/11/map-vs-foreach-1.png)
Map vs forEach in 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:
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} ποΈ`);
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](https://allma.si/blog/wp-content/uploads/2020/11/map-vs-foreach-1-1024x1024.png)
![Why Do You Need to Know About Functional Programming?](https://miro.medium.com/max/1400/1*6ouhL3OQsqXDZJ7HyTutKA.png)
Resources:
![Mentoring](/assets/img/mentoring.png)
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: