Have you ever needed to loop over your array and wasn’t sure which method to use? forEach()
and map()
seemingly do the same thing, right? So which one do you choose and what exactly is the difference between them? In this quick guide, I’ll go over the one thing that sets these two methods apart. If you’re unfamiliar with forEach()
or map()
and would like to learn more, checkout these guides below where I go over them.
MDN documentation:
Consider the following code using forEach()
:
const users = ['John', 'Sam', 'Kate']; users.forEach(user => { console.log(user.toLowerCase());
}); // expected output: 'john'
// expected output: 'sam'
// expected output: 'kate'
Now, the same code but using the map()
method:
const users = ['John', 'Sam', 'Kate']; users.map(user => { console.log(user.toLowerCase());
}); // expected output: 'john'
// expected output: 'sam'
// expected output: 'kate'
There really is no difference between the two example above other than one is using the forEach
method and one uses the map()
method. So what’s the difference? Well, map()
will actually return a new, updated array with the logic ran in the function.
Instead of using the console to log our outputs, lets just take our element parameter and run the toUpperCase()
method on it and see what happens. Check out the following code:
Using forEach()
:
const users = ['John', 'Sam', 'Kate']; users.forEach(user => user.toLowerCase()); // expected output: undefined
Using map()
:
const users = ['John', 'Sam', 'Kate']; users.map(user => user.toLowerCase()); // expected output: ['JOHN', 'SAM', 'KATE']
As you can see, forEach()
doesn’t return anything whereas map()
returns a new array with the results of the logic ran. It’s a pretty small difference between the methods and they both have their use cases. If you ever need something returned as a result of your logic, use the map()
method. If you don’t need anything returned and just need to alter the content of an array, use the forEach()
method.
I hope this quick run-through of the difference between forEach()
and map()
were helpful and you feel confident choosing the right method in your projects going forward!