About the let Scope

Hey guys,

I’m trying to understand the logic here


'use strict';
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"

a. In the first and second iteration i === 2 is false because i is 0 and then 1. So the code inside if statement is not execute.

b. In the third iteration i === 2 is true, so the code entinside curly braces is execute and the value of i in the return statement is 2.

c. Then the for loop is running for last time, 3 < 3 is false, so the code exits from the for loop and console.log(printNumTwo()); print 2 in the console.

The i inside the if statement scope is 2 (same the function scope)

But what’s interesting is:
The i of the for loop declaration reach to 3 (3 < 3) but The i inside the for loop scope keeps to be 2.

It’s happens because 2 things?
a. it’s scope is inside the for declaration (because let)
b. also because the for loop exits when the loop reach to 3, and never can’t get inside again to assign 3, and imidaily reach to the line of the function call to prints 2?

Hi,
variables declared with the “let” keyword exist only in the block for which they are defined, as well as in any contained sub-blocks (and not the parent block).
That means that the variable i, defined inside the for loop is not accessible in the outer block.
This is the reason why console.log(i); says that i is not defined.
For console.log(printNumTwo()); you are actually invoking the function printNumTwo.
You can do so because, while iterating the for loop, you reach a point where you assign a function to the variable printNumTwo. Had you not entered inside the if structure, you wouldn’t have been able to call printNumTwo().

Even if the for loop had continued its iteration (for a certain amount of steps, not indefinetly), the function would have still returned 2, because that was the only value of the index i when you assigned the function to the variable printNumTwo.
Also, this assignment is locked behind an if that lets you enter ONLY when the index is 2.

2 Likes

Besides what @simonebogni said, You should read how data is passed to functions (not just functions, but ‘around’ in general). Here is a great answer for JavaScript. JavaScript uses call by sharing.

2 Likes

Awesome, I got it, great explanation.
Thank you both :sunglasses:
@skaparate @simonebogni

1 Like