start learning
Image 1
44757857547

While loop

The "while loop" in JavaScript is a looping construct that repeatedly executes a block of code as long as a specified condition remains true. It's particularly useful when you want to repeat a certain task while a condition is met, and you might not know the exact number of iterations in advance.

The basic syntax of a "while loop" in JavaScript is as follows:


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

Here's how the "while loop" works:

  1. The condition is evaluated before each iteration. If the condition is true, the loop's block of code is executed; otherwise, the loop terminates.
  2. The loop continues as long as the condition remains true.
Example:

var count = 0;

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

In this example, the loop starts with count at 0, checks if count is less than 5, executes the code block, increments count by 1, and then repeats the process until count is no longer less than 5.

The "while loop" is suitable when you want to repeat a task based on a condition that might change during each iteration. Be cautious with your condition to avoid infinite loops—loops that never terminate if the condition is always true.