ProgrammingJavascriptCareerProductivityGadgetsASP.NETWeb Design

Iterating through arrays in JavaScript

Written by
Published on
Modified on
Filed under

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 Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

No messages posted yet

Developer Poll

Q:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks