DEV Community

Vidya
Vidya

Posted on

Looping in JavaScript

What is a Loop?
A loop is used to repeat a block of code until a certain condition is met. It saves time and makes your program shorter and cleaner.

For Loop:
The for loop runs a block of code a specific number of times.

Syntax:
     for(initialization; condition; increment){
      // code to be executed
     }
Enter fullscreen mode Exit fullscreen mode
Example:
        for (let i=1; i<=5; i++) {
          console.log("Number: " + i);
        }

  output --> Number:1
                Number:2
                Number:3
                Number:4
                Number:5
Enter fullscreen mode Exit fullscreen mode

While Loop:
The while loop runs code as long as the condition is true.

Syntax:
     While (condition) {
     // code to be executed
     }
Enter fullscreen mode Exit fullscreen mode
Example:
         let i=1;
        while (i <= 3) {
          console.log("Hello" + i);
          i++;
        }

   output --> Hello 1
               Hello 2
               Hello 3
Enter fullscreen mode Exit fullscreen mode

Do....While Loop:
The do..while loop runs at least once, even if the condition is false.

Syntax:
    do{
      // code to be executed
    } while (condition);
Enter fullscreen mode Exit fullscreen mode
Example:
        let i=1;
        do{
           console.log("Count: " + i);
           i++;
        } while (i <= 3);

   output ---> Count:1
               Count:2
               Count:3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)