JavaScript – Loop over Elements of an Array

To loop over elements of an array in JavaScript, we can use Array.forEach() method, or any other looping statement like For Loop, or While Loop.

In this tutorial, we will go through each of these looping techniques to iterate over elements of an array.

Loop over Array using Array.forEach

The syntax to use Array.forEach() to iterate over element of array, and having access to the item itself and the index during each iteration is

array.forEach(function(item, index, array) {
    //code
})

In the following example, we take an array with three elements, and loop over the items using Array.forEach() method.

Example

ADVERTISEMENT

Loop over Array using For Loop

The syntax to use For Loop to iterate over element of array arr is

for(var index = 0; index < arr.length; index++) {
    var element = arr[index];
    //code 
}

In the following example, we take an array with four elements, and loop over the items using For Loop.

Example

Loop over Array using While Loop

The syntax to use While Loop to iterate over element of array arr is

var index = 0;
while (index < arr.length) {
    var element = arr[index];
    //code
    index++;
}

In the following example, we take an array with four elements, and loop over the items using While Loop.

Example

Conclusion

In this JavaScript Tutorial, we learned how to loop over Array elements in JavaScript, with examples.