The while loop
- Node.js course
- Beginner
- Lesson 43/116
- 4 min
Learn loops that run while a condition holds with while.
The while loop
A loop that runs while a condition is true uses while. The form is while (condition) { ... }. The condition is tested before each iteration; if true the body runs, if false the loop ends.
For example let n = 3; while (n > 0) { console.log(n); n--; } prints 3, 2, 1. Note: without n-- the loop runs forever. In while you write the counter update inside the body yourself; forgetting it leads to an infinite loop.
while vs for
for suits cases where the iteration count is known, while suits cases where the count depends on a condition. In for the init, condition and step are on one line; in while only the condition is there, the rest you write.
For example when reading user input until they type "quit", while is natural: while (input !== "quit") { ... }. For counted cases for is shorter and clearer. Both can do the same job; the choice depends on context.
Practice Count down from 3
Write a while loop: start with let n = 3;, condition n > 0. In the body first call console.log(n), then n--. The output must be three lines: 3, 2, 1.
Starter code
// Write the while loop starting with let n = 3;Sample solution
let n = 3;
while (n > 0) {
console.log(n);
n--;
}Expected output
3 2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each part to its job
| Term | Meaning |
|---|---|
while |
Starts the loop |
(condition) |
Tested each iteration |
n-- |
Decrements counter |
{ ... } |
Body |
2 What is the output of let n = 2; while (n > 0) { console.log(n); n--; }?
let n = 2;
while (n > 0) { console.log(n); n--; }- 1 2
- 2 1 0
- 2 1 Correct answer
- 0 1 2
Explanation: n starts at 2, prints down to but not including 0; 2, 1.
3 Write the while header
let n = 3;
____ (n > 0) {
console.log(n);
n--;
}
let n = 3;
while (n > 0) {
console.log(n);
n--;
}
Explanation: while builds a conditional loop.