How to iterate an array in javascript? (the proper way)



In this tutorial we are going to explain how to loop through all the objects in an array using JavaScript. This tutorial aims beginner developers and we will shown several ways to solve the problem.

Using for each

forEach parameter could be a function. The function passed by parameter accepts one parameter, which will be an element in the array.

Here is an example using a function to log values of an array:

var a = [1, 2, 3];
a.forEach(function(entry) {

You can also pass a function with two or three parameters. Parameters of the function are (in order):

  • The value of each entry
  • The index of that entry
  • Reference to the array you're iterating over

forEach runtime cost or complexity

We tested the performance of looping through a 10000-entry array both with and without calling a function.

Looping the array took: * Without function ~4500 times in a second. * With the function ~2000 times in a second.

Using the function is slower, however looping the whole array took only 2.78 microseconds of overhead.

Naive for loop

You can always loop the array using a generic for loop:

var index;
var a = [1, 2, 3];
for (index = 0; index < a.length; ++index) {

In the code we just use the length of the array to loop from 0 and access the elements using the index.

Using for-in

We don't recommend the for-in for array iteration since it could complicate the code, take a look to the following code:

var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These are explained
        /^0$|^[1-9]\d*$/.test(key) &&    // and then hidden
        key <= 4294967294                // away below
        ) {

As you can see there are some strange things like the if condition. For in loops through the enumerable properties of an object, not the indexes of an array. This force the code to filter the properties to match the index of the arrays. Order is also not guaranteed.

About more ways

There are more ways to iterate the array, for example using for-of. For the beginner javascript developer it should be enough for now, but in the future or if you are an intermediate developer we recommend to look for more ways to iterate array.

Appendix: ES5 defined another ways of looping an array

ES5 defined several other useful "work your way through the array and do things" functions, including:

  • every: stops looping the first time the iterator returns false
  • some: stops looping the first time the iterator returns true
  • filter: creates a new array with filtered elements
  • map: creates a new array with a function applied to each element