WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to loop through an array in JavaScript

Topic: JavaScript / jQueryPrev|Next

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

See the tutorial on JavaScript ES6 features to learn about the new features introduced in ES6.


Related FAQ

Here are some more FAQ related to this topic:

Your Feedback:

We would love to hear from you, please drop us a line.