How map() and forEach() are alike, but different

Sometimes in code, certain methods seem to be redundant until you look under the hood. The .map() and .forEach() are two such methods — mostly the same, but also different. When I first began learning to code, it was easy for me to be confused about these two JavaScript methods. Maybe some of you have felt the same way.

In this article, I’d like to take a moment to demystify some of the differences between .map() and .forEach().

I’ll start by showing you two code examples, which are essentially the same. I’ll be swapping out the methods .forEach() and .map().

In this example, I am simply iterating over an array of numbers and getting the square root of each. Next, I’m logging the result to the console and displaying it on the page using .innerHTML.

Here’s the example using .map():


<h2 id = “result1”></h2>


var exampleOne = [10, 20, 30];
var result1 =;
var h21 = document.getElementById(“result1”);
h21.innerHTML = result1;

Try this code in your favorite code editor. Look at it using the console in your browser. You’ll see that this code correctly found the square root of each number in the array. It also printed the information to the console and displayed it on our page. We achieved the desired result!

Next, let’s try an almost identical piece of code, using .forEach()


<h2 id = “result2”></h2>


var exampleTwo = [40, 60, 80];
var result2 = exampleTwo.forEach(Math.sqrt);
var h22 = document.getElementById(“result2”);
h22.innerHTML = result2;

If you test out this code for yourself, you’ll see that it returns ‘undefined’. That’s because .map() iterates over the array and returns the results of each iteration in a new array. But ForEach() simply iterates over the array without returning the result.

The purpose of .forEach() is to execute a function for each iteration of an array. Our .map() is a sort of multi-tasking method that also executes a function for each iteration of an array. At the same time it also returns the results of the execution in a new array.

I have a slight preference toward the .map() method. But that does not discount the fact that .forEach() is also very useful in some circumstances.

Here’s a very simple example in which .forEach() works well:

var exampleThree = [“cat”, “dog”, “bird”];
var result3 = exampleThree.forEach(function(d) {
return d;

In this case, .forEach() returns the strings ‘cat’, ‘dog’ and ‘bird’ one at a time in order in the console. One word is returned for each iteration of the array. We need an inner function inside our .forEach() for it to return the result.

I hope this has helped to clarify the differences in behavior between .map()and .forEach(). Using this knowledge, you’ll be able to choose wisely when deciding what method to use in your next project!