JavaScript Loops
Loops are a way of repeating code. They're handy for repetitive tasks. Loops are used for actions that need to run a particular number of times or until a certain condition is true.

Syntax of the Loops

1. while loop

Use the while statement to create a loop that executes code as long as a condition is true. 
let counter = 0;
while ( counter < 10 ) {
  console.log( counter );
  counter += 1;
}
While loop check the condition before it executes, so the console will print the value of the variable counter for 10 times.

The execution of the code starts from line 1 - line 5, then it repeat the line 2 - line 5 for 9 times and it stops when the value of the counter becomes 10. 

2. do...while Loop

Use do...while to create a loop that executes code until the test condition is false. 
let counter = 0;
do {
  console.log( counter );
  counter += 1;
} while ( counter < 10 )
do…while loop check the condition after it executes, so the console will still print the value of the variable counter for 10 times, but it will at lease execute one time if the condition is false at the beginning.
let counter = 0;
do {
  console.log( counter );
  counter += 1;
} while ( counter < 0 )

3. for Loop

The for loop is a more compact variation of the while loop, with similar parts, and it's useful when you know how many times you want to repeat an action. So the for loop is the most common one in use.
for ( let i = 0; i < 10; i++ ) {
  console.log( i );
}
*Normally we use the variable i as the counter.
Same as the output of the while loop, the console will print out number 0-9 in order:

4. Reference


  • Avoid Infinite Loops
One important concept you should keep in mind about loops is the infinite loop. An infinite loop, as the name suggests, is a loop that keeps running forever. If the test condition is always true, the loop never stops, and your program will crash because of this. So you should always make sure that your test condition can stop the loop at some point.

Application of the Loops

Loops are also frequently used to go through an array or a list one element by another.

1. Loop Through Arrays

If we can loop through an array, we can use all the elements and do something with them, like add them up and calculate the average: