let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns "i is not defined"
What is difference?
Challenge: Compare Scopes of the var and let Keywords
let is block scoped, it only exists in the block (normally denoted by {} in JS) in which it’s defined. Once you go past the end of that block, the variable doesn’t really exist anymore, it gets cleaned up. So in the loop, i is declared (for (let i =), then once you go past the closing } and the loop is finished, let goes out of scope and doesn’t exist any more. var hangs around, even though it isn’t needed. The let behaviour is more useful 99.9% of the time, it is basically a fixed var and should be preferred.
variables declared with var are function scoped, it means that the i of the loop is a global variable (as it is not contained in any function).
The loop works that before it execute the i++ and then check if it satisfy the i < 3 requirment. So after the loop the i has value of 3 as that is the first value that fails the check
note that if you were to do
let i;
for (i = 0; i < 3; i++) {}
console.log(i) // this prints 3
why would you ask it prints 3? well, because you have declared the variable outside the block scope of the loop, so it is a global variable
if you instead do
for (let i = 0; i < 3; i++) {}
console.log(i); // reference error!
why this time there is an error? well, because i is declared inside the loop, as such it exist only inside the loop