Repeat while a condition stays true.

while-loop A `while` loop checks its condition before every iteration. The loop body must move the state toward stopping.

While Loops

start
while_loop.js
Replay: real traced execution (multi-file project)
const start = 3;
let value = start;
let steps = 0;
while (value > 0) {
  value -= 1;
  steps += 1;
}

console.log("start=" + start);
console.log("steps=" + steps);
const start = 1;
let value = start;
let steps = 0;
while (value > 0) {
  value -= 1;
  steps += 1;
}

console.log("start=" + start);
console.log("steps=" + steps);
const start = 5;
let value = start;
let steps = 0;
while (value > 0) {
  value -= 1;
  steps += 1;
}

console.log("start=" + start);
console.log("steps=" + steps);
  1. start ← 3, value ← 3, steps ← 0

    1const start→ 3 = 3; //@start=1, 52let value→ 3 = start→ 3;3let steps→ 0 = 0;4while (value > 0) {
  2. value ← 2, steps ← 1

    pass 1 of 3
    2let value = start;3let steps = 0;4while (value3 > 0) {5  value -= 1;6  steps += 1;7}
    values this step1steps
    All 3 passes — pass 1 is the card above
    passvaluesteps
    13 21
    22 12
    31 03
  3. console.log("start=" + start);

    6  steps += 1;7}89console.log("start=" + start3);10console.log("steps=" + steps3);
    outputstart=3
    steps=3
  1. start ← 1, value ← 1, steps ← 0

    1const start→ 1 = 1;2let value→ 1 = start→ 1;3let steps→ 0 = 0;4while (value > 0) {
  2. value ← 0, steps ← 1

    2let value = start;3let steps = 0;4while (value1 > 0) {5  value -= 1;6  steps += 1;7}
    values this step1steps
  3. console.log("start=" + start);

    6  steps += 1;7}89console.log("start=" + start1);10console.log("steps=" + steps1);
    outputstart=1
    steps=1
  1. start ← 5, value ← 5, steps ← 0

    1const start→ 5 = 5;2let value→ 5 = start→ 5;3let steps→ 0 = 0;4while (value > 0) {
  2. value ← 4, steps ← 1

    pass 1 of 5
    2let value = start;3let steps = 0;4while (value5 > 0) {5  value -= 1;6  steps += 1;7}
    values this step1steps
    All 5 passes — pass 1 is the card above
    passvaluesteps
    15 41
    24 32
    33 23
    42 14
    51 05
  3. console.log("start=" + start);

    6  steps += 1;7}89console.log("start=" + start5);10console.log("steps=" + steps5);
    outputstart=5
    steps=5