ES6 - Compare Scopes of the var and let Keywords

Can someone please explain why the line console.log(i); prints 3. From what I understand, “i” is declared within the scope of just the for loop and shouldn’t be available outside it not outside it.

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

you sound correct to me

1 Like

Right?! I just can’t see how the code makes any sense.

using var makes it a global variable and it can be used out of the scope of forloop. Use let instead of var so that doesn’t happen

1 Like