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
?