JavaScript While Loop

The while loop in JavaScript is used to execute a block of code repeatedly as long as a specified condition evaluates to true.

1. Syntax of while Loop:

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

Try It Now

Explanation:

  • condition: An expression evaluated before each iteration. If the condition is true, the loop runs; otherwise, it stops.

2. Basic Example of while Loop:

let count = 0;

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

Try It Now

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

Try It Now

Explanation:

  • The loop starts with count = 0 and increments count by 1 in each iteration.
  • The loop runs as long as count < 5.

 

3. Example with User Input:

let input;

while (input !== "stop") {
    input = prompt("Type 'stop' to end the loop:");
    console.log("You entered: " + input);
}

Try It Now

Explanation:

  • The loop continues to prompt the user for input until they type "stop".

 

4. Infinite Loop (Use with Caution):

A while loop can become an infinite loop if the condition never evaluates to false. This can cause the browser or script to freeze.

while (true) {
    console.log("This will run forever unless stopped!");
}

Try It Now

Note: Ensure that the loop has an exit condition to avoid infinite loops.

 

5. while Loop with break:

You can use the break statement to exit the loop prematurely.

let count = 0;

while (count < 10) {
    console.log("Count: " + count);
    if (count === 5) {
        break;
    }
    count++;
}

Try It Now

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Try It Now

6. while Loop with continue:

The continue statement skips the current iteration and moves to the next one.

let count = 0;

while (count < 5) {
    count++;
    if (count === 3) {
        continue;
    }
    console.log("Count: " + count);
}

Try It Now

Output:

Count: 1
Count: 2
Count: 4
Count: 5

Try It Now

Explanation:

  • When count equals 3, the continue statement skips the rest of the loop body for that iteration.

7. Using while Loop for Array Iteration:

let fruits = ["Apple", "Banana", "Cherry"];
let index = 0;

while (index < fruits.length) {
    console.log(fruits[index]);
    index++;
}

Try It Now

Output:

Apple
Banana
Cherry

Try It Now

Explanation:

  • The loop iterates through the array elements until all elements are printed.

Conclusion:

  • The while loop is ideal for situations where the number of iterations depends on a dynamic condition.
  • It is important to ensure that the condition eventually becomes false to avoid infinite loops.
  • Using break and continue provides additional control over loop execution.