While Loops In Javascript

Posted on December 29, 2024 by Vishesh Namdev
Python C C++ Javascript Java
While and do-while Loop in JS

What is while loop
The while loop in JavaScript is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. It’s useful when you don’t know in advance how many times the loop should run.

Syntax
while (condition) {
  // Code to execute as long as the condition is true
}

Example

let count = 0;
while (count < 5) {
          console.log("Count is: " + count);
  count++; // Increment the count to avoid an infinite loop
  }

Explanation:

  • The loop starts with count = 0.
  • It checks the condition count < 5. If true, it executes the code inside the loop.
  • The count variable is incremented by 1 each time the loop runs.
  • Once count reaches 5, the condition becomes false, and the loop stop.
  • What is do-while loop?
    The do-while loop in JavaScript is a control flow statement that executes a block of code at least once, and then repeatedly executes the block as long as a specified condition is true. It differs from the while loop because the condition is checked after the code block is executed, ensuring the block runs at least once.

  • do: Contains the block of code to execute.
  • while: Contains the condition that determines if the loop will run again.
  • Syntax
    do {
        // Code to execute
    } while (condition);

    Example

    let count = 0;
            do {
                console.log("Count is: " + count);
                count++;
            } while (count < 5);

    Explanation:

  • The do block executes once with count = 0.
  • After the first execution, the while condition count < 5 is checked.
  • As long as the condition is true, the loop continues.
  • Once count reaches 5, the condition becomes false, and the loop stops.
  • Difference between For, While and do-while Loop
    📢Important Note📢