agyanadda@gmail.com

JS While Loop

Conditions and Loops 1 min read Updated Dec 1, 2026 Topic 16 of 38

A while loop repeats as long as a condition is true. Use it when you do not know in advance how many times to repeat.

let i = 1;
while (i <= 5) {
  console.log(i);
  i++;
}

do...while

Runs the block at least once, then checks the condition:

do {
  answer = prompt('Type yes');
} while (answer !== 'yes');

Remember

Change the variable inside the loop, or it will never stop.

Example

Example — Doubling until 1000 HTML
<pre id="out"></pre>

<script>
  let amount = 1;
  let days = 0;
  let text = '';
  while (amount < 1000) {
    amount *= 2;
    days++;
    text += `Day ${days}: ₹${amount}\n`;
  }
  text += `\nIt took ${days} days to cross ₹1000.`;
  document.getElementById('out').textContent = text;
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which loop always runs at least once?

Exercise 2 True / False

A while loop checks its condition before each round.

Exercise 3 Fill in the Blank

If the condition never becomes false, you get an ___ loop.

Frequently Asked Questions

Use for when you know the number of rounds (like 1 to 10). Use while when you repeat until something happens.