How to loop over an array in javascript ?

Active March 01, 2022    /    Viewed 99    /    Comments 0    /    Edit


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

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount