Hi @hlhnicola !
So I’ve been racking my brain over this one for a few minutes. I sat here thinking exactly the same thing and couldn’t for the life of me understand why 3 was being returned instead of 2… and then EUREKA! And boy do I feel stupid now…
Actually, I say that, but quite frankly the formatting of the example code could be improved here.
So here we go:
- We have a for loop. As i’m sure you’ve picked up by now for loops work in this pattern…
set variable (var i = 0; in this case) --> execute following code (numArray.push(i)) where condition is true (i<3) --> do something at the end of each iteration (increment i with i++).
- We can follow through each iteration of the loop to see what happens!
i starts as 0
i is less than 3 so i (0 at the moment) is pushed to the array
i is incremented by 1 to become 1
i starts as 1
i is less than 3 so i (1 at the moment) is pushed to the array
i is incremented by 1 to become 2
i starts as 2
i is less than 3 so i (2 at the moment) is pushed to the array
i is incremented by 1 to become 3
i starts as 3
i is NOT LESS THAN 3 so loop ceases execution
- So at this point our loop has ended. Notice how when i is incremented in the third iteration that it takes the value 3, this is what causes the loop to exit (before executing code) on the next iteration.
This is why now, when we get the console to log i, it returns 3.
I find it really helps to work through iterations of loops in situations like this!