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

</>
Copy
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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var arr = ['apple', 'banana', 'cherry'];
        arr.forEach(function(item, index, arr) {
            document.getElementById('output').innerHTML += '<p>' + index + ' - ' + item + '</p>';    
        })
    </script>
</body>
</html>

Loop over Array using For Loop

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

</>
Copy
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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var arr = ['apple', 'banana', 'cherry', 'mango'];
        for(var index = 0; index < arr.length; index++) {
            var element = arr[index];
            document.getElementById('output').innerHTML += '<p>' + index + ' - ' + element + '</p>';    
        }
    </script>
</body>
</html>

Loop over Array using While Loop

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

</>
Copy
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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var arr = ['apple', 'banana', 'cherry', 'orange'];
        var index = 0;
        while (index < arr.length) {
            var element = arr[index];
            document.getElementById('output').innerHTML += '<p>' + index + ' - ' + element + '</p>';    
            index++;
        }
    </script>
</body>
</html>

Conclusion

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