We've seen how for...of
loops work with arrays. But what if we don't have an array and just want to repeat something a specific number of times, like 5 times?
For this, JavaScript has another, more traditional, for
loop.
Engagement Message
Ready to see how this works?
The traditional for
loop uses a counter to keep track of the repetitions. It looks a bit more complex, but it gives you precise control over how many times the loop runs.
Engagement Message
How might you tell a friend to clap their hands 3 times, by counting?
This for
loop has three parts inside its parentheses, separated by semicolons:
- Initialization:
let i = 0
(start a counteri
at 0). - Condition:
i < 3
(keep looping as long asi
is less than 3). - Final Expression:
i++
(add 1 toi
after each loop).
Pretty cool, right?
Engagement Message
Can you spot these three parts in other for loops you see?
