DEV Community

Cover image for JavaScript: When should I use forEach and map?
Samanta Fluture
Samanta Fluture

Posted on

JavaScript: When should I use forEach and map?

Whenever I advance in JavaScript course classes, I noticed that the moment I leave the conventional loop and go to a forEach, many students get a little lost at the beginning and the idea of ​​this post is to immortalize this explanation in text, helping whoever it is. my student or student, how much you may have this doubt right now.

Introduction

If you take the 3 codes below, they will all have the same return in the browser.

const names= ['Whinds', 'Freeway', 'Teste', 'Maria'];

for(let i = 0; i < names.length; i = i + 1 ) {
    console.log('[for]', names[i]);
}
Enter fullscreen mode Exit fullscreen mode
const names = ['Whinds', 'Freeway', 'Teste', 'Maria'];

names.forEach(function(name, i) {
    console.log('[forEach]', name, i);
})
Enter fullscreen mode Exit fullscreen mode
const names = ['Whinds', 'Freeway', 'Teste', 'Maria'];

names.map(function(name, i) {
    console.log('[forEach]', name, i);
})
Enter fullscreen mode Exit fullscreen mode

At first, you can assume that if the result is the same, they do the same thing. But it is clear if we look a little at forEach and map that here we don't have to worry about an index variable (which we usually call i), which is used to control the looping as it is an element that is normally incremented or decremented.

However, it is easy to notice that while we don't write it, this data is accessible to us, only this time we receive it as an argument of the function that we pass to forEach and map. To make this clearer, let's take a look at a possible implementation of forEach.

The implementation doesn't work in the array.map and array.forEach models, because for that we would need to mess with the prototype and that alone yields a post.

Understanding forEach

Earlier we saw that forEach loops through all the items in an array, just like the normal for loop, this is because internally it has a for lop. If we were to implement it, it would come out something like the code below:

function ourForEach(arr, function) {
    for(let i = 0; i < arr.length; i = i + 1) {
        function(arr[i], i);
    }
}

ourForEach(['name', 'name2'], function(name, index) {
    console.log(name, index)
})
Enter fullscreen mode Exit fullscreen mode

Whenever you are going to do a for loop, it's worth using a forEach, as it eliminates the mental burden of having to deal with control variables and therefore can help make the code easier to read, taking into account that this is an overused form in the JavaScript world in general.

Understanding the map

In practice, as we saw at the beginning of the post, map and forEach seem to do the same thing, but the difference comes when we analyze the return of what comes out of them, the difference is clear.

const names = ['Whinds', 'Freeway', 'Teste', 'Maria'];

const returnForEach = names.forEach((currentName) => {
    console.log(currentName);

    return currentName.toUpperCase();
})
console.log(returnForEach) // undefined
Enter fullscreen mode Exit fullscreen mode
const names= ['Whinds', 'Freeway', 'Teste', 'Maria'];

const returnMap = names.map((currentName) => {
    console.log(currentName);

    return currentName.toUpperCase();
})
console.log(returnMap ) // ['WHINDS', 'FREEWAY', 'TESTE', 'MARIA']
Enter fullscreen mode Exit fullscreen mode

While the forEach was made to be an alternative to the for loop, the map was made to do a transformation/alteration operation on the items of an array and at the end of these operations we have a new list with the same number of items as the base list.

If we were to implement the map, we would end up with code on this line:

function ourMap(arr, function) {
    const newArray = [];
    for(let i = 0; i < arr.length; i = i + 1) {   
        newArray .push(function(arr[i], i));
    }    
    return newArray 
}

ourMap(['name', 'name2'], function(name, index) {
    console.log(name, index)
})
Enter fullscreen mode Exit fullscreen mode

This makes it easier for us to concatenate operations such as making a map and adding a filter, given that the map's return is an array, we can write code on this line: .map().filter().

Conclusion

That's all for this post, I hope it was clear that if we just want a more elegant way to work with for, we use .forEach and if we want to transform/change values ​​or even concatenate operations on top of arrays, .map is the most suitable .

Top comments (2)

Collapse
 
justmedev profile image
justmedev

You forgot to include for ... of ...

Collapse
 
gfierro profile image
Greg Fierro

A little proof reading before posting would go a long way. Interesting topic.