LESSON 14
While Loops
Learning objective: Repeat code while a condition stays true.
Understand
A while loop runs as long as its condition is true.
Use while when you do not know in advance how many times to repeat. Make sure something inside the loop moves the condition toward false, or you get an infinite loop.
Analogy: A while loop is like scooping water until the bucket is empty — you stop when the condition changes.
See It in Action
Counting down:
let n = 3;
while (n > 0) {
console.log(n);
n--;
}How it works: The loop prints
n and decreases it each pass, stopping when n reaches 0.Try It Yourself
- Write a while loop that counts down from 5.
- Ensure it decreases each pass.
- Confirm it stops at 0.
Quick Quiz
When is a while loop a good choice?
Challenge
Use a while loop to count down from a number to zero.
Success condition: Your loop counts down and halts at zero.
+10 XP
Lesson Complete
You answered correctly and completed the required practice. Your progress has been saved on this device.
Continue to next lesson →