Last time we used for (let i = 0; i < 3; i++)
but didn't do much with the variable i
itself. That variable is called the loop counter, and it holds useful information!
Engagement Message
What do you think the variable i
represents in each round of the loop?
In for (let i = 0; i < 3; i++)
, the variable i
takes on the values 0, then 1, then 2. We can use this variable inside our loop to create different behavior each time.
Engagement Message
If we used for (let i = 0; i < 5; i++)
, what would be the last value that i
holds inside the loop?
Here's how we can use the loop variable:
This prints "This is round number 1", then 2, 3, and 4.
Engagement Message
What would be printed on the third time through this loop?
The loop counter is especially helpful when working with arrays. We can use it to access specific index positions:
