Search

How to loop through an array in JavaScript

post-title

Use the JavaScript for Loop

The easiest way to loop through or iterate over an array in JavaScript is using the for loop.

The following example will show you how to display all the values of an array in JavaScript one by one.

<script>
var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
    
// Loop through the fruits array and display all the values
for(var i = 0; i < fruits.length; i++){
    document.write("<p>" + fruits[i] + "</p>");
}
</script>

Alternatively, you can use the ES6 newly introduced for-of loop to iterate over an array, like this:

<script>
var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
    
// Loop through the fruits array and display all the values
for(var fruit of fruits){
    document.write("<p>" + fruit + "</p>");
}
</script>