while

Repeats a block of code while the condition is true. The condition is checked before every turn.

On this page

Example

#
JavaScript
let fuel = 10
let trips = 0

while (fuel >= 3) {
  fuel -= 3
  trips++
}

console.log(`Trips: ${trips}, fuel left: ${fuel}`)
Console
Trips: 3, fuel left: 1

Definition and usage

#

A while loop checks the condition, and if it’s true, runs the block and goes back to checking again. When the condition is false right away, the block never runs.

It comes in handy when you don’t know the number of repeats up front: waiting for a result to cross a threshold, draining a queue, or searching until you find something. When the number of turns is known, for is usually more convenient.

Something inside the loop eventually has to make the condition false. Without that, the loop runs forever and locks up the page. As an emergency measure, you can stop it with break.

Syntax

#
Syntax
while (condition) {
  // statements
}

More examples

#
Processing a queue
JavaScript
const queue = ['Task 1', 'Task 2', 'Task 3']

while (queue.length > 0) {
  const task = queue.shift()
  console.log(`Checking: ${task}`)
}

console.log(queue)
Console
Checking: Task 1
Checking: Task 2
Checking: Task 3
[]
An unknown number of repeats
JavaScript
let points = 5
let rounds = 0

while (points < 100) {
  points *= 2
  rounds++
}

console.log(points, rounds)
Console
160 5

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Before running it, make sure the variable in the condition changes on every turn. An infinite loop freezes the browser tab.
  • If the block needs to run at least once, for example when asking the user for input, use do...while.

Related entries

#

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