while

The while statementopen in new window creates a loop that executes the block of code as long as the condition is true. The condition is evaluated before executing the block of code.

let count = 0

while (count < 20) {
  count++
}

console.log(count) // 20

The above example, may look familiar because it is the same structure that is used by the for statement, which is the preferred method.

for (let count = 0; count < 20; count++) {...}

The while statement does have one advantage over the for statement, and that is to create a loop when the number of iterations is unknowable. This can occur if the condition is based on a random event, such as flipping a coin.

// flip the coin until heads appears (heads = 0, tails = 1)
let coin = 1

// will continue looping until coin = 0 
while (coin) {
  coin = Math.round(Math.random())
  console.log(coin)
}

do...while

The do...while statement is a variation of the while statement. Like the while statement, it creates a loop that executes a block of code while the condition is true. However, the condition is evaluated after executing the statement, resulting in the block of code executing at least once.

// flip the coin until heads appears (heads = 0, tails = 1)
let coin

// set the value of the coin first
do {
  coin = Math.round(Math.random())
  console.log(coin)
}
while (coin) // loop until coin = 0

This YouTube video was created by Steve Griffith.