While Loops
Count down to lift-off with while.
1let countdown = 3;
2while (countdown > 0) {
3 console.log(countdown);
4 countdown = countdown - 1;
5}
6console.log("Lift off!");
$ node main.js
3
2
1
Lift off!
Every line, explained
let countdown = 3;- let creates a variable whose value you PLAN to change later. The modern rule of thumb: use const unless you know the value will change; then use let. (You may see var in old code; it went out of style years ago.)
while (countdown > 0) {- A while loop repeats its block for as long as the condition in the brackets is true. The condition is checked again before every trip around the loop. Here it keeps going while countdown is greater than 0.
console.log(countdown);- console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. Prints 3, then 2, then 1.
countdown = countdown - 1;- Takes 1 off countdown each trip. Without this line the loop would never end!
}- This } closes the while loop.
console.log("Lift off!");- console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. Outside the loop: it runs once, after the loop has finished.