How to loop over an array in javascript ?

Published: March 01, 2022

Updated: December 09, 2022

Tags: Javascript; Array;

DMCA.com Protection Status

Examples of how to loop over each items of an array in javascript:

Create an array in javascript

Let's create a very simple array in javascript

var data = [9,5,7,3,1,4];

Note that we can test if it is an array using the following method:

console.log( Array.isArray(data) );

which gives

True

here.

To get the size of an array:

console.log( data.length );

gives

6

And to get a given element by index:

console.log( data[0] );

returns

9

and

console.log( data[3] );

returns

3

and

console.log( data[6] );

returns

undefined

Loop over an array using a for loop

To loop over an array in javascript a straightforward solution is to use a for loop:

for (var i = 0; i < data.length; i++){
    console.log( data[i] );
}

gives

9
5
7
3
1
4

Using for ... of

Another solution in javascript is to use for ... of

for (var item of data ){
    console.log( item );
}

also gives:

9
5
7
3
1
4

Using forEach()

Another solution using Array.prototype.forEach()

var data = [9,5,7,3,1,4];

data.forEach(item => console.log(item));

returns

9
5
7
3
1
4

Nested array:

Let's now consider a nested array ['a','b','c']:

var data = [9,['a','b','c'],7,3,1,4];

to loop over all items, a first solution is to use array.flat() method:

var data_flatted = data.flat()

console.log( data_flatted );

gives

[9, 'a', 'b', 'c', 7, 3, 1, 4]

Then

for (var i = 0; i < data_flatted.length; i++){
    console.log(data_flatted[i]);
}

gives

9
a
b
c
7
3
1
4