Order of operation?

Tell us what’s happening:
Hi all,

I’m struggling to understand why the code returns 3 in the lesson example. What’s the order of operation such that the result is 3?

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36.

Challenge: Compare Scopes of the var and let Keywords

Link to the challenge:

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.

Thank you. But why does the If logic get ignored completely? Why does 2 never get returned.

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.

Another option is to use Closure.

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

Thank you! I’ll have to look into more.

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.