Skip to content

JavaScript array loop | Ways of iterating over an array

  • by

JavaScript array supports almost all loop statements. Using Loops you can iterate over an array. This means do something repeatedly or execute a block of code a number of times.

Loops are very useful you can run the same code over and over again, each time with a different value.

Supporting Loops statements in Javascript

Here are some statements for loops provided in JavaScript are:

  • for statement
  • do…while statement
  • while statement
  • forEach method

Examples of JavaScript array loops

Let’s see the examples of Array work with for, do-while, while, etc.

for loop statement

A for loop repeats until a specified condition evaluates to false.

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    array = [ 1, 2, 3, 4, 5, 6 ]; 
	for (index = 0; index < array.length; index++) { 
    	console.log(array[index]); 
	} 
    </script> 
      
    
</body> 
  
</html> 

Output:

Examples of JavaScript array loops

Using a while loop

A while statement executes its statements as long as a specified condition evaluates to true.

<script type="text/javascript"> 

    index = 0; 
	array = [ 1, 2, 3, 4, 5, 6 ]; 
  
	while (index < array.length) { 
    	console.log(array[index]); 
    	index++; 
	}
    </script> 

forEach method

The forEach method calls the provided function once for every array of items in the order.

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    index = 0; 
	array = [ 1, 2, 3, 4, 5, 6 ]; 
  
	array.forEach(myFunction); 
	function myFunction(item, index){
	 
    	console.log(item); 
	}
    </script> 
      
    
</body> 
  
</html> 

do…while statement

The do…while statement repeats until a specified condition evaluates to false.

<script type="text/javascript"> 

    let result = '';
	let i = 0;

	do{
  		i = i + 1;
  		result = result + i;
	}while(i < 5);

	console.log(result);
	
    </script>

Output: 12345

Do comment if you have any doubts, questions, and suggestions on this tutorial. All loops are almost similar to other programming languages.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
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