I think people are missing the actual point of your question so i’ll post a copy of my response to the same question on an identical thread:
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!
Now then, if you’re thinking to yourself “but if the printNumTwo function only gets called when i === 2, how can we call it when i is not 2?”, then you wouldn’t be alone because I did exactly this as well.
Whats important here is that the printNumTwo function is called WITHIN THE LOOP WHEN i === 2. We can still call on this specific function anywhere else as we normally would. Heck, all this function does is return i so the final line console.log(printNumTwo()) is essentially identical to console.log(i). As we can see from the end of our third iteration of the loop i === 3
Hope this helps!