Understanding scopes of 'var' and 'let'

Please tell me if my understanding of what is happening is right.

At the point in the loop when i ===2 the function() { return i}; is assigned to the global var printNumTwo. The loop then increments up by 1 so that i = 3. It fails the condition i < 3, so the code is not executed again, but the way I understand it is that even if the loop condition fails, i++ still has already incremented i up to 3 and because i is global that’s why the function returns it as 3?

var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 3

Close.
Javascript hoists the scope of var outside of this function, while changing to let will prevent this hoisting.

1 Like

var is a function scope, that means if you declare it in a function, you can access it anywhere in the function.
let is a block scope, that means it can only be accessed inside the block ({}) that it was declared.
ex:

function exampleFunc() {

  for (var variable1 = 1; variable1 < 10; variable1++){

 }
 console.log(variable1) /*will output 1. You can access it from 
anywhere inside the function */

 for (let i = 1; i < 10; i++) {
//i can only be accessed here and nowhere else.
}
console.log(i) /* This in the other hand will output an error 
that says "i" is not declared, because i is declared on the block
above this log thus it can only be accessed there.
}

A lot of programmer take use of this by being able to use the same dummy variable more than once inside the same function. Ex:

function myFunction() {
  for (let i = 1; i < 20; i++) {
     //codes here
  }
 //you can re-use the variable again, because it is only declared
 //inside the for loop block {}

for (let i = 10; i < 100; i += 10) {
//codes here
}

}

The function above would not give out an error saying that i is already declared.

1 Like

It’s not quite so clean cut. You can always shadow a variable inside of an inner scope. For example,

var name = "Bob"

function printName() {
  var name = "Joe"

  for (var i = 0; i < 1; i++) {
    var name = "Tim"
    console.log(name)
  }
}

printName();
1 Like