Menu

Iterating through arrays in JavaScript

In this post we will go over the various ways that you can iterate through a given array in JavaScript.

We will also go into when to use the various methods and when not to use them.

Using the map() function

The map() method will return a new array with the new values that are attained from running the passed in function on each item in that array.

var scores = [10, 30, 50];
                
var doubledscores = scores.map(function(item, index){
    item * 2;
});
            

Note that this will not update the original array.

For that reason, it should not be used if you are not going to use the resulting array, and should instead use a for loop or forEach method.

forEach() method

The forEach() function will iterate through each item in a given array and run a passed in callback function on each item.

Unlike the map() method above, it will return undefined and should not be used to modify a given array.

var scores = [10, 30, 30];
var total = 0;
                    
scores.forEach(function(item){
    total += item;
});
                    
console.log(total);
// will return 70

for...of method()

And lastly, the for...of statement creates a loop that will iterate through any iterable objects.

var scores = [0, 20, 30];
                    
for (const item of scores){
    console.log(item);
}

Note that the for...of statement will iterate through any iterable object, such as strings, maps and sets.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet

Add a comment