Control flow · Lesson 12 of 45
Loops: for and while
Repeat something without writing it again and again.
9 minutes4 games
A for loop has 3 parts in its brackets, separated by ;:
- start:
let i = 1(runs once). - condition:
i <= 3(keep going while true). - step:
i++(after every round).
Step by step1 / 11
- ▶let total = 0
- 2for (let i = 1; i <= 3; i++) {
- 3 total += i
- 4 console.log("i =", i, "total =", total)
- 5}
Variables
| total | 0 |
Output
…
Press “Play” and watch i and total change.
while and do…while
while repeats while its condition is true; it suits cases where you don't know the number of rounds in advance. do…while is the same but always runs at least once before checking.
JavaScript
let coins = 3
while (coins > 0) {
console.log("Spend a coin, left:", coins - 1)
coins--
}
let tries = 0
do {
tries++
} while (tries < 1)
console.log("tries:", tries)break and continue
JavaScript
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue // skip even numbers
if (i > 7) break // stop completely
console.log(i)
}Complete the code
Complete the loop to print 0 to 4.
for (let i = ; i < ; i++) { console.log(i) }
Spot the bug
This loop never ends. Where's the problem?
What's the output?
for (let i = 0; i < 6; i++) {
if (i === 2) continue
if (i === 4) break
console.log(i)
}What will this code print?
Exercise
Print the sum of 1 to 10 (the result is 55).
Expected output: 55
JavaScript
let sum = 0
Learn more from
Played 0 of 4 games
Sign in to save your progress and earn XP.