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>
Use the JavaScript
forLoopThe easiest way to loop through or iterate over an array in JavaScript is using the
forloop.The following example will show you how to display all the values of an array in JavaScript one by one.
Alternatively, you can use the ES6 newly introduced for-of loop to iterate over an array, like this:
need an explanation for this answer? contact us directly to get an explanation for this answer