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>