ES6: Compare Scopes of the var and let Keywords; How is i === 3, I dont see where i was declared

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords

Hey I am reading over this exercise, it keeps talking about how I was declared as 3 in the global scope, I see the Array and I see the loop that says to cycle through the array as long as i < 3. I dont see anywhere where I is equal to 3. Can you point me to where it is declared as 3 in global scope? thanks

-How does console.log(i) return 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

-How does console.log(i) return 3?

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

1 Like

Because the last time the for loop goes, i is equal to 2. But it hasn’t failed the test yet so it checks, it increments i to 3 and sees that i<3 is now longer true and exits the loop. So, at this point i is equal to 3.

2 Likes

Hi Morty,

This explains it in more detail

The idea is that in the for loop var = i is declared

var numArray = [];
for (var i = 0; i < 3; i++) {
  numArray.push(i);
}

It’s understood by the program as

var numArray = [];
var i;
for (var i = 0; i < 3; i++) {
  numArray.push(i);
}

As kevinSmith said once the loop is finished its final value is i = 3 . It is also still available so when you do console.log(i) it returns 3.