JavaScript Control Flow Loops

While loop

A while loop is a special case of a for loop used often enough that there is a reserved keyword and syntax for it, and iterates as long as the condition is truthy.

The syntax for a while loop is written below.

while (conditionExpression) {
// loop body
}

It is assumed that mutations within the loop body or from some external source eventually make the while loop condition falsy; otherwise it will run forever.

Code example: re-implementation of while

const myWhile = (condition, body) => {
for (;condition;) {
body()
}
}

A while loop is essentially a for loop without an initializer or an incrementer expression.

Code example: count down from 5

let x = 5
while (x >= 0) {
console.log(x)
x--
}
// 5
// 4
// 3
// 2
// 1
// 0