DEV Community

Raja B
Raja B

Posted on

Loop for While

while loop:

  • When the number of iterations is unknown, but the condition is known
A while loop is used when you do not know 
how many times a task will be repeated, 
but you know the condition 
that must be met before the loop stops.
Enter fullscreen mode Exit fullscreen mode

Real-life Example: Charging a mobile phone. The phone continues charging until the battery reaches 100%. It may take 20 minutes or 50 minutes (the exact number of repetitions is unknown), but the charging process continues as long as the battery is not fully charged.

Input:

        let battery = 90; 

        while (battery < 100) 
       {
            battery++; 
      console.log("Charging... Current level: " + battery);

        }

    console.log("Battery is fully charged! 
Please unplug the charger.");
Enter fullscreen mode Exit fullscreen mode

Output:

while loop

Quick Memory Trick (Cheat Sheet):

Ascending Order (< or <=):

When you want to go from a smaller number to a larger number,
say:

"Run as long as our counter i is less than the larger number."
(Usually, we use i++ to increase the counter.)

Descending Order (> or >=):

When you want to go from a larger number to a smaller number, say:

"Run as long as our counter i is greater than the smaller number."
(Usually, we use i-- to decrease the counter.)

Input:

        let i = 1;

        while (i <= 5) {
            console.log(i);
            i++; 
        }
Enter fullscreen mode Exit fullscreen mode

Output:

ascn

Input:

        let i = 5;

        while (i >= 1) {
            console.log(i);
            i--; 
        }
Enter fullscreen mode Exit fullscreen mode

Output:

descn

Top comments (0)