Loops and Ranges
While Loops
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
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);
start ← 3, value ← 3, steps ← 0
1const start→ 3 = 3; //@start=1, 52let value→ 3 = start→ 3;3let steps→ 0 = 0;4while (value > 0) {value ← 2, steps ← 1
pass 1 of 32let value = start;3let steps = 0;4while (value3 > 0) {5 value -= 1;6 steps += 1;7}values this step1stepsAll 3 passes — pass 1 is the card above pass valuesteps1 3 → 2 1 2 2 → 1 2 3 1 → 0 3 console.log("start=" + start);
6 steps += 1;7}89console.log("start=" + start3);10console.log("steps=" + steps3);outputstart=3 steps=3
start ← 1, value ← 1, steps ← 0
1const start→ 1 = 1;2let value→ 1 = start→ 1;3let steps→ 0 = 0;4while (value > 0) {value ← 0, steps ← 1
2let value = start;3let steps = 0;4while (value1 > 0) {5 value -= 1;6 steps += 1;7}values this step1stepsconsole.log("start=" + start);
6 steps += 1;7}89console.log("start=" + start1);10console.log("steps=" + steps1);outputstart=1 steps=1
start ← 5, value ← 5, steps ← 0
1const start→ 5 = 5;2let value→ 5 = start→ 5;3let steps→ 0 = 0;4while (value > 0) {value ← 4, steps ← 1
pass 1 of 52let value = start;3let steps = 0;4while (value5 > 0) {5 value -= 1;6 steps += 1;7}values this step1stepsAll 5 passes — pass 1 is the card above pass valuesteps1 5 → 4 1 2 4 → 3 2 3 3 → 2 3 4 2 → 1 4 5 1 → 0 5 console.log("start=" + start);
6 steps += 1;7}89console.log("start=" + start5);10console.log("steps=" + steps5);outputstart=5 steps=5