Predict JavaScript while Loop Output
Predict OutputBeginner
Question
What does this code print?
Code
let n = 3;
while (n > 0) {
console.log(n);
n = n - 1;
}
Hint
The loop runs while n is greater than 0. Trace each iteration.
Explanation
Iteration 1: n is 3, prints 3, then n becomes 2. Iteration 2: n is 2, prints 2, then n becomes 1. Iteration 3: n is 1, prints 1, then n becomes 0. Now n > 0 is false, so the loop stops. The output is three lines: 3, 2, 1.
Related Resources
Related Lessons
- Loops
Learn how JavaScript while loops work.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.