while
Repeats a block of code while the condition is true. The condition is checked before every turn.
Example
#let fuel = 10
let trips = 0
while (fuel >= 3) {
fuel -= 3
trips++
}
console.log(`Trips: ${trips}, fuel left: ${fuel}`)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
#while (condition) {
// statements
}More examples
#const queue = ['Task 1', 'Task 2', 'Task 3']
while (queue.length > 0) {
const task = queue.shift()
console.log(`Checking: ${task}`)
}
console.log(queue)let points = 5
let rounds = 0
while (points < 100) {
points *= 2
rounds++
}
console.log(points, rounds)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
#- do...whileRuns a block of code at least once, then repeats it while the condition is true.
- 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.