do...while

Runs a block of code at least once, then repeats it while the condition is true.

On this page

Example

#
JavaScript
let attempts = 0

do {
  attempts++
  console.log(`Attempt ${attempts}`)
} while (attempts < 3)
Console
Attempt 1
Attempt 2
Attempt 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

#
Syntax
do {
  // statements
} while (condition)

More examples

#
The block runs even though the condition is false
JavaScript
let lives = 0

do {
  console.log('Game start, lives:', lives)
} while (lives > 0)

while (lives > 0) {
  console.log('This never prints')
}
Console
Game start, lives: 0
Finding the first free code
JavaScript
const taken = ['A1', 'A2', 'A3']
let number = 0
let code

do {
  number++
  code = `A${number}`
} while (taken.includes(code))

console.log(code)
Console
A4

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...while less often than while or for. Reach for it when “at least once” genuinely follows from the program’s logic.

Related entries

#

Spotted a mistake or missing an example? Write to us.