JavaScript

How to Loop/Iterate Through an Array in JavaScript

Loops are key components of every programming language. They are used to run the same code or logic again and again in a cycle. Usually loops have an index value which is different each time the loop repeats. There are different kinds of loops available in JavaScript which help us iterate over an array. An array is a collection that is used to store different elements; An example of an array in JavaScript is:

const names = ['John', 'Chris', 'Harry'];

To get an element from this array we just provide index and the name of the array:

console.log(names[2]);


This will return “Harry” as the indexing starts from 0.

We have seen that we can get an element from an array by specifying an index number. But it would be too hectic if there were 100 names in the above-mentioned array. The solution is using loops; loops can easily handle arrays with numerous entries. This post is focussing on how we can use JavaScript loops to iterate over an array to be an efficient programmer.

Note: The browser console is used for the demonstration of examples in this article.

How to iterate through an array using JavaScript for loop

A for loop is a loop which repeats an action as long as a certain condition is true. When the condition becomes false, the loop breaks. The syntax of for loop in JavaScript is similar to that in Java or C; The simplest for loop syntax is:

for(initialize variable; some condition;  variable increments/decrements){
    //some code to be executed
}

Example of iterating through a for loop over an array is:

const names = ['John', 'Chris', 'Harry'];

for(let index = 0; index < names.length; index++){

    console.log(names[2]);
}


We first declared an array named names, then a for loop and initialized a variable called index inside the for loop; This will act as the index for the array. After that, we put the condition that the loop should run till it is one less than array length i-e from 0 to 2 (3 times in total). The last parenthesis tells the loop that for every cycle increment the index by 1. Every cycle of the loop, we console logged the array elements one by one using the variable initialized that is index.

To put it simply, the loop starts at the 0th index and then the length of the array is checked. If the condition is true then loop runs the block of code that is inside the parentheses which is console logging. After this, it increments “index” and then checks the condition again. Same cycle repeats until the specified condition is no longer true.

How to iterate through an array using JavaScript while loop

Syntactically, JavaScript while loop is also similar to C or Java while loop. Example of iterating an array using while loop in JavaScript is:

const names = ['John', 'Chris', 'Harry'];

index=0;

while(index<names.length){

console.log(names[index]);
index++;
}

How to iterate through an array using JavaScript for/of loop

The for/of loop is also used to loop through the items/elements of an array:

const names = ['John', 'Chris', 'Harry'];

for (name of names) {

    console.log(name);
}
}

How to iterate through an array using JavaScript forEach loop

The forEach() method calls or executes a specified callback function for each element in the array. It takes three arguments; the current item/element, index and the array itself.

const names = ['John', 'Chris', 'Harry'];

names.forEach(element => {
   console.log(element);
});

In the example above we have used an arrow function which takes the current element of the array as an argument inside the .forEach() loop to console.log each element.

How to iterate through an array using map method in JavaScript

The Map() method iterates over an array by creating a new array. For every element in the original array, it executes some function i.e. the arrow function with num as an argument in the below given example. It doesn’t change the original array. Now suppose we have an array of numbers from 1 to 5. We want each number to multiply by 2. We can achieve this as follows:

let table1 = [1,2,3,4,5];
let table2 = table1.map(num => num * 2);

console.log(table2);

How to iterate through an array using every method in JavaScript

The every() method tests whether every element of the array passes a condition implemented by the provided function; it executes a function once for every element. It returns either true or false depending upon whether every element passed the test or not:

const isLessThanTen = (currentValue) => currentValue < 10;

const arr = [1, 3, 4, 3, 5, 7];

console.log(arr.every(isLessThanTen));

Now if we change the array in the above example:

const arr = [1, 3, 16, 3, 5, 7];

Conclusion

In JavaScript arrays are a data type which are used to store similar kinds of data; this data can be easily accessed and manipulated by using different loops and methods provided by JavaScript. In this post we covered the basics of iterating over an array in JavaScript. We also discussed iterating through an array from for, while, for/of, forEach() loop, map() and every() method.

These are not the only methods that can be used to iterate over an array. There are dozens more. The ones we discussed are the widely-used methods by the developers iterating over an array.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.