0

could anyone tell me why console.log(i); returns 3?

var numArray = []; for (var i = 0; i < 3; i++) { numArray.push(i); } console.log(numArray); // returns [0, 1, 2] console.log(i); // returns 3

1 Answer 1

4

Because after i is 2 and pushed to numArray, it's incremented to 3. However, this fails to meet the condition that i < 3, so the loop is exited, however i remains as 3 which is why you see it in console.log. The key point to understand is that in JavaScript loops, the incrementer code i++ is applied at the end of each iteration, but the conditional check is applied at the start of each iteration, which is why this occurs.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the clarification. I still am not sure why the same rule applies to console.log(numArray);. How come the end of the array returns "2" not "3" ? Sorry I'm still a beginner.
Because the numArray pushing only happens after the conditional - so only when I is less than 3 will the push run.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.