JavaScript loop through Array | Example code

JavaScript loop through Array means a execute a block of code a number of times using a loops statement. It’s also called Array iteration (repeating steps)

Here are several options:

  • Sequential for loop
  • Array.prototype.forEach
  • ES6 for-of statement

Example of JavaScript loop through Array

Let’s see one by one every method exampels:

1. Sequential for loop statement

This is easiest way and Works on every environment.

Output:

JavaScript loop through Array for loop

Read more: JavaScript array loop

2. Array forEach method

The ES5 specification introduced a lot of beneficial array methods, one of them, the Array.prototype.forEach and it gives us a concise way to iterate over an array:

Let’s see example of adding a number

Output: 125

Read more: JavaScript foreach loop Example

3. ES6 for-of statement

This method should be avoided.

It shouldn’t be used for array-like objects because:

  • The order of iteration is not guaranteed; the array indexes may not be visited in numeric order.
  • Inherited properties are also enumerated.

Output: red
green
blue

Do comment you suggestions and doubts below in the comment section.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.