while
A loop that runs as long as its condition is true. Use it when you don’t know how many iterations you’ll need upfront.
When to use it
- Unknown count — keep going until a condition changes
- Polling — retry until a result arrives
- Processing streams — read chunks until the end
- Game loops — run until a player wins or quits
Anatomy
// while — check condition first, then run body
while (condition) {
// runs as long as condition is truthy
// make sure something inside changes the condition or it loops forever
}
// do...while — run body first, then check condition (always runs at least once)
do {
// runs at least once, even if condition is false
} while (condition)At a glance
| Variant | When it checks | Minimum runs |
|---|---|---|
while | Before each iteration | 0 — may never run |
do...while | After each iteration | 1 — always runs once |
1. Simple — countdown
let count = 3
while (count > 0) {
console.log(count) // 3, 2, 1
count-- // decrement or this loops forever
}2. Intermediate — process until done
// walk up the DOM tree from an element to the root
function getAncestors(el) {
const ancestors = []
let current = el.parentElement
while (current) { // null when we reach the top
ancestors.push(current)
current = current.parentElement // move up one level
}
return ancestors
}3. Advanced — retry with backoff
async function fetchWithRetry(url, maxRetries = 3) {
let attempt = 0
while (attempt < maxRetries) {
try {
const res = await fetch(url)
if (res.ok) return await res.json()
throw new Error(`HTTP ${res.status}`)
} catch (err) {
attempt++
if (attempt >= maxRetries) throw err
// exponential backoff: 1s, 2s, 4s...
const delay = 1000 * 2 ** (attempt - 1)
await new Promise(r => setTimeout(r, delay))
}
}
}Gotchas
Infinite loops
// forgetting to update the condition = frozen page
while (true) {
// nothing changes — this runs forever
}
// always ensure the loop can exit
let i = 0
while (i < 10) {
i++ // this makes the condition eventually false
}do…while vs while
let input = ''
// do...while runs the body first — prompt always shows at least once
do {
input = prompt('Enter "yes" to continue')
} while (input !== 'yes')
// while might never run — if input were already 'yes', the body is skipped
while (input !== 'yes') {
input = prompt('Enter "yes" to continue')
}Related
- for — better when you know the iteration count
- .forEach() — for looping over arrays
Last updated on