JavaScript

How to loop through an array in JavaScript

The easiest way to loop through an array in JavaScript is to use the “for” loop. The following example will show you how to display all the values in an array in JavaScript, one by one.
 

Example 1: How to loop through an array in JavaScript
var colors = ["Blue", "Red", "Orange", "Green"];
    
// loop through the array and display all the values 
for(var i = 0; i < colors.length; i++){
    document.write(" " + colors[i] + " ");
}

Output:

Blue Red Orange Green
 

Example 2: How to loop through an array in JavaScript

You can also use ES6’s new “for-of” loop to iterate through an array, like the following example:

var colors = ["Blue", "Red", "Orange", "Green"];
    
// loop through the array and display all the values 
for(var color of colors){
    document.write(" " + color + " ");
}

Output:

Blue Red Orange Green
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *