Iterating through arrays in JavaScript

Written by
Published on
Modified on

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 =, 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;
    total += item;
// 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){

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.


No messages posted yet

Developer Poll 🐱‍💻


Add a comment

Send me your weekly newsletter filled with awesome ideas