Beginner · 9 min
Counted loops and while loops
Repeat a known number of times or continue until a condition becomes false.
Use a counter
A for loop has an initializer, a condition, and an update. Check the condition before each pass and update the counter afterward.
for (let count = 1; count <= 3; count += 1) {
console.log(count);
}Output
1 2 3
Move toward stopping
A while loop repeats while its condition is true. Its body must eventually change the condition or explicitly leave the loop.
let remaining = 3;
while (remaining > 0) {
remaining -= 1;
}
console.log(remaining);Output
0
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Count study sessions
Set total to the sum of 1 through 4 using the loop, then display total.
Include 4 by using <= in the loop condition.