Skip to content

JavaScript loop through Array | Example code

  • by

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

1. Sequential for loop statement

This is easiest way and Works on every environment.

<!DOCTYPE html> 
<html> 
<body> 
        <script> 
        var arr1 = ["A", "B", "C", "D"]; 
        var arrayLength = arr1.length;
        
        for (var i = 0; i < arrayLength; i++) {
            console.log(arr1[i]);
            //Do something
            }
        </script>     
</body> 
</html> 

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.

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 
 
    var sum = 0;
	var numbers = [65, 44, 12, 4];
	numbers.forEach(myFunction);
 
	function myFunction(item) {
  	sum += item;
	}
 
	alert(sum)
	
    </script> 
      
    
</body> 
  
</html> 

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.
 <!DOCTYPE html> 
    <html> 
    <body> 
            <script> 
            let colors = ['red', 'green', 'blue'];
            for (const color of colors){
                console.log(color);
            }
            </script>     
    </body> 
    </html> 

Output: red
green
blue

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

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading