forEach or mix between
forEach inconsistently. At the end of the day, both methods iterate over an array. That’s why it’s important to understand the differences between these methods and figure out when to use each one.
Map is a method that creates a new array by running a function on each element of the original array. The result of this function becomes a new value in the new array. It’s perfect for cases where you want to transform all the elements in the array.
Here’s a simple example - let’s double the numbers in an array.
const numbers = [1, 2, 3]; const doubled = numbers.map(num => num * 2);
The main benefit of using
map is that it won’t change the original array, but will return a brand-new one instead. Use
map when creating a new array with transformed elements based on the original array. In other words - you care about the new, returned value, so you are mapping the input array to an output array.
forEach is a method that goes through an array and runs a function on each element. It’s ideal when you need some action to take place for each element.
Here’s a simple example - let’s log each number in the array.
const numbers = [1, 2, 3]; numbers.forEach(num => console.log(num));
The main benefit of using
forEach is that it’s easy to read and understand, making your code more maintainable. Use
forEach when you need to perform an action for each element of the array, but don’t need a new array. In other words - you don’t care about the returned value but need the operation to happen.
map returns a new array, while
forEach returns undefined.
Immutability and side effects:
map doesn’t change the original array, while
forEach may cause side effects if you modify the array within the loop. That’s why when you see any array modification methods inside a
forEach it’s a code smell.
What if we use swap them?
Of course, both functions can be utilized to achieve the same, but we strive to write good and idiomatic code. Let’s use previous examples, but swap the functions used.
Let’s start by doubling the numbers with
forEach. Problem is that forEach doesn’t return value, so we need a new array, so the example would look like this:
const numbers = [1, 2, 3]; const doubled = ; numbers.forEach(num => doubled.push(num * 2));
It results in more lines and uses an additional function, but many beginners write code just like this.
console.log each number with a
const numbers = [1, 2, 3]; numbers.map(num => console.log(num));
This would work, just looks bad. The last line returns
[undefined, undefined, undefined], and no way we would use this value, so using a
map in this context makes it misleading.
forEach have their unique uses:
map for creating new arrays with transformed elements and
forEach for performing actions on each element, when we don’t care for the returned value. Choose the right method based on your needs, so your code communicates your intentions well.