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.

 

How Lack of Rest Can Impact Your Finances Small Businesses Can Enhance File Management Following these Tips How Much Do Real Estate Agents Spend on Marketing? How to Engage Your Online Audience for Long-Lasting Success Why is Plagiarism Such a Big Deal? Resume Service Review: Why Everyone Should Use It
adbanner