do. . . while
Runs a block of code at least once, then repeats it while the condition is true.
Example
#let attempts = 0
do {
attempts++
console.log(`Attempt ${attempts}`)
} while (attempts < 3)Definition and usage
#A do...while loop works like while, but it checks the condition only after running the block. That means the code inside always runs at least once, even if the condition is false from the start.
It’s the natural choice when you need to do something first and only then evaluate the result: generate a value and check whether it fits, ask the user a question and repeat it on a bad answer, or fetch the first batch of data.
Variables declared with let or const inside the block aren’t visible in the condition. Whatever you check in while (...) should be declared before the loop.
Syntax
#do {
// statements
} while (condition)More examples
#let lives = 0
do {
console.log('Game start, lives:', lives)
} while (lives > 0)
while (lives > 0) {
console.log('This never prints')
}const taken = ['A1', 'A2', 'A3']
let number = 0
let code
do {
number++
code = `A${number}`
} while (taken.includes(code))
console.log(code)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Declare the variable used in the condition before
do, since the loop body has its own scope. - You’ll see
do...whileless often thanwhileorfor. Reach for it when “at least once” genuinely follows from the program’s logic.
Related entries
#- whileRepeats a block of code while the condition is true. The condition is checked before every turn.
- forA loop with a counter: initialization, condition, and step. Repeats a block of code while the condition is true.
- breakImmediately ends a loop or a switch statement and moves on to the code right after it.
- continueSkips the rest of the current loop turn and moves straight to the next one.
Spotted a mistake or missing an example? Write to us.