I was going through the basics of javascript on freecodecamp just to refresh my memory and when I got to ES6 and the explanation of the differences between var and let, one of the examples gave me (and my colleagues) a headache.
'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"
I was expecting the printNumTwo
function to return undefined
, thinking that by the time it was called the variable i
did not exist. One of my colleagues said that when the function expression was assigned to the variable, the i
got a value of 2
so when you call the function it will always return 2
.
To test this theory, we modified the original example to this:
'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
i++;
}
}
console.log(printNumTwo());
// returns 3
console.log(i);
// returns "i is not defined"
To everyone's surprise calling the function after the for loop returns 3
instead of 2
or the originally expected undefined
.
Can anyone please shed some light on why is this behavior? What really happens when you assign a function expression to a variable or when you call such one?