Lecture 6 – JavaScript Loops

Sometimes, you need to execute a statement repeatedly while writing a program. There is no need to write separate lines of codes for each of these statements. All you need to do is to use JavaScript loops and they will do the rest.

JavaScript supports all types of loops, considerably reducing pressure on the programmers.

The While Loop

While Loop is the most basic form of loop in JavaScript. If the statement is true, the while loop will keep on executing the code without any stop. The loop automatically terminates once the statement becomes false. The syntax of the while loop is as under.

<!DOCTYPE html>
<html lang="en">
<head>
    
</head>
<body>
        <body>   
                
                    
                    while (expression) {
  Execute the statement if expression is true
}
                       
                           
</body>

</html>

We will implement while loop using the following example.

<!DOCTYPE html>
<html lang="en">
<head>
    
</head>
<body>
       
  
    var number = 10;

      while (number ");
        number++;
      }

      document.write("Loop stopped!");
          
</body>

</html>

The output of the above code will be as under.

The Do While Loop

The Do While Loop, unlike While Loop, checks for the condition at the end of the loop. Even if the condition is untrue, the Do Loop will execute at least once. The syntax of the Do Loop is as follows.

do {
   Execute the statement if expression is true;
} while (expression);

You should always put semicolon at the end of the Do loop.

The following example will further elucidate the Do loop.

<!DOCTYPE html>
<html lang="en">
<head>
    
</head>
<body>
       
  
    var number = 0;
            
            do {
               document.write("Current number : " + number + "
"); number++; } while (number </body> </html>

The above code will produce the following result.

The For Loop

The For Loop is the most complex loop in JavaScript. It consists of three parts which are as under.

  • Loop Initialization: we start our loop and set our counter to starting value in this stage. In fact, the loop begins after the initialization phase is complete.
  • The Test Statement: the interpreter evaluates the condition and determines whether it is true or false. The code inside the loop will be executed if the condition is true. If not, the control will leave the loop.
  • The Iteration Statement: This is the place where we increase or decrease the counter.

Here is the syntax of For Loop.

for (initialization; test condition; iteration statement) {
Execute statement if condition is true
}
<!DOCTYPE html>
<html lang="en">
<head>
    
</head>
<body>
       
  
     var number;
         
            for(number = 10; number ");
            }         
          
</body>

</html>

Here is the output of the above code.

In the next lecture, we will study JavaScript Arrays and Functions