Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript while Loop

The while loop runs as long as its condition is true.

It is best when you do not know the number of iterations ahead of time.

Why We Need It

Many tasks depend on dynamic conditions like retries or input validation.

while loops handle these cases cleanly when written with safe exit conditions.

Syntax

while (condition) { ... }

Basic Example

1. Basic while

let i = 0;

while (i < 3) {
  console.log(i);
  i++;
}

Runs until the condition is false.

Real World Example

2. Retry loop

let attempts = 0;
let success = false;

while (attempts < 3 && !success) {
  attempts++;
  success = attempts === 2;
}

console.log(attempts, success);

Use while for retry logic.

Multiple Use Cases

Unknown Iterations

Use while loops when you do not know how many times you will iterate.

They run as long as the condition remains true.

Exit Conditions

Always ensure the loop condition can become false.

Update counters or state inside the loop to avoid infinite loops.

Polling and Retries

while loops are common for retries, polling, and reading input until valid.

Combine with break statements for early exits.

More Examples

3. Read input

const numbers = [2, 4, 6, 9];
let idx = 0;

while (idx < numbers.length && numbers[idx] % 2 === 0) {
  idx++;
}

console.log(idx);

Stop when a condition fails.

4. Guard with break

let count = 0;

while (true) {
  count++;
  if (count === 3) break;
}

console.log(count);

Use break to exit early.

Comparison

Without

let i = 0;
if (i < 3) {
  console.log(i);
  i++;
} // repeats manually

With

let i = 0;
while (i < 3) {
  console.log(i);
  i++;
}

Common Mistakes and Fixes

Infinite loop

Ensure the condition changes inside the loop.

Missing increment

Update the counter or state each iteration.

Overly complex conditions

Extract conditions into named variables for clarity.

Using while for fixed counts

Prefer for loops when the count is known.

Interview Questions

What is the main risk with while loops?

Infinite loops if the condition never changes.

When should you prefer for loops?

When the number of iterations is known.

How do you exit early?

Use break inside the loop.

Practice Problem

Practice: Use a while loop to count down from 5 to 1.

let i = 5;
// TODO: count down

One Possible Solution

let i = 5;
while (i > 0) {
  console.log(i);
  i--;
}

Frequently Asked Questions

When should I use while?

When the number of iterations is not known in advance.

How do I stop a while loop?

Make the condition false or use break.

Is while slower than for?

Not meaningfully; choose based on readability.

Try It Yourself

Try changing the condition to see how many iterations run.