i is a global variable, when the printNumTwo function runs it returns whatever i was set to in the last loop iteration. You can run the code through a visualizer to help see it.
The logic is not ignored. The function declaration happens when the if statement is true.
However, that does not mean it will return what i was at time of function declaration. The function is called (not declared) after the for loop is done and the i variable has been increment to 3. The i variable is not scoped to the for loop because it was declared using var. If you use let for the variable it will be block scoped and return 2.
function getValueAtDeclaration() {
for (var i = 0; i < 3; i++) {
if (i === 2) {
return function () {
return i;
};
}
}
};
// functionName()(); runs the return function
console.log(getValueAtDeclaration()()); // 2
I just happened to come across this question. So, here is my understanding of this:
var printNumTwo; // declare a variable name printNumTwo, the printNumTwo is undefined. Then run to the next line of codes.
for (var i = 0; i < 3; i++) { //Running this loop
if (i === 2) { //enter into the condition i ===2
printNumTwo = function() {
return i;
};
// printNumTwo is now assigned to an anonymous function will return i, but it has not done anything yet because at this state, it has not been called yet;
//The loop keeps running after assigning the variable printNumTwo, “i” now equals to 3. The loop stops after the i = 3, the next line gets executed.
}
}
console.log(printNumTwo()); //Console.log the function printNumTwo which now will return the current value of “i” and we know “i” now equals to 3 which is why the loop stops running and this line of code executes.