Console.log Say What?

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

Why does console.log(i) return 3?

Because you declared the variable i with ‘var’ instead of ‘let’. ‘var’ puts the variable i in global scope which means it exists outside of the for loop. So after the for loop has finished looping the last value of i is 3.

If you use ‘let’ then the variable i has block scope which means it only exists inside of the for loop. Change it to ‘let’ and see what happens when you try to print i to the console after the for loop.

Thanks, makes sense. Wouldn’t it be undefined since i wouldn’t exist oustide the for loop.

if you use let that’s what’s going to happen. let is block scoped, var is function scoped

Because The value of i is increasing first and then the condition is checked. As the Condition is false it didnt revert the value of i, so the final value of i is 3

Did you try using ‘let’? It does not technically have a value of ‘undefined’ because it doesn’t exist outside of the for block. Just try it and you will see what happens when you try to access a variable that doesn’t exist.

I replaced all the var words with let and got:

ReferenceError: i is not defined

Exactly, you get an error. ‘undefined’ is a valid value in JS. But if you use ‘let’ in the for loop then i does not exist outside of that loop and thus trying to access it doesn’t give you ‘undefined’ it gives you an error.

The console will print the result of evaluating an expression. The result of evaluating console.log() is undefined since console.log does not explicitly return something. It has the side effect of printing to the console.