Use while when you do not know ahead of time how many iterations you need.
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) that returns an array containing numbers from n down to 1, using a while loop. For example, countdown(5) → [5, 4, 3, 2, 1].collatz(n) that returns the number of steps to reach 1 using the Collatz sequence:
n is even: n = n / 2n is odd: n = 3 * n + 1#output: "Countdown from 5: 5,4,3,2,1".A while loop keeps running as long as its condition is true.