Can't understand different between let and var!

can anyone explain me what this two code exactly do?

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

////////////////////////////////////////////////////////////////////////////

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

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/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.

2 Likes

I got that thank you.
and another thing that I can’t understand why it returns 3 in var?

2 Likes

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

2 Likes

Yes, you are right. Now I can understand what’s really going on Thanks a lot for your response.

1 Like