How to loop through an array in JavaScript

Answer: Use the JavaScript for Loop

JavaScript offers a simple way to loop through, iterate over, or loop through arrays using the for -a-loop function.

The following example will illustrate how JavaScript displays all of the values in an array.

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

You could also use the ES6 recently introduced  for-of loop in order to iterate over an array such as 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>

JavaScript ES6 features tutorial to learn more about the features included in ES6.

 

Exit mobile version