Use a condition to decide whether another iteration is needed, and update the value each time.
Use while when you repeat until a condition changes. The countdown task has a known starting value; the later Collatz task repeats until the value reaches 1. Both need an update inside the loop or they would keep running.
while looplet count = 0;
while (count < 5) {
console.log(count);
count++;
}
The condition is checked before each iteration. If count starts at 5, the loop body never runs.
do...while loopThe condition is checked after each iteration — so the body always runs at least once:
let num = 0;
do {
console.log(num);
num++;
} while (num < 3);
countdown(n) using while to return the integers from n to 1 in an array. The provided one-item probe should print Countdown one: 1.collatz(n) using while to count steps until 1 (even: halve; odd: triple and add 1). The provided one-item probe should print Collatz one: 0.Countdown three: 3,2,1 using countdown(3).Collatz six: 8 using collatz(6).Countdown from 5: 5,4,3,2,1.A while loop keeps running as long as its condition is true.
Always update the variable inside the loop to avoid infinite loops.
A do-while loop always runs at least once.