Scope: Having difficulty understanding this example

Hi all,

I was pretty sure I understood scope, but this example is making me scratch my head.

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

The console.log line returns “3” instead of “2”. I can’t really describe why that’s happening yet because in my brain I see the for loop running until i is equal to 2.

I think what I’m not completely sure about is the “printNumTwo = function…” portion.

Anyone care to explain what I’m missing? I can usually throw in a debugger or a console.log and start to understand what’s going on, but not quite sure this time.

Thanks so much in advance.

A for loop has a few steps to execution

for (initialize; condition; increment)}
  body
}
  1. initialize

  2. execute the body

  3. increment

  4. check loop condition, and repeat from 2 or stop

In this case, the loop stops when i < 3 is false

The confusion arises from the fact that variables declared with var are globally scoped. Although your loops stops at i==2, the value of i is actually still incremented till 3 at which point the condition i < 3 becomes false and so the loop exits.

The i variable having been declared with var keyword will be equal to 3 at the time you reach console.log(printNumTwo()) because again the i is globally scoped with var and so effects the last increment globally.

To avoid this behavior, consider using the let keyword to declare variables as it is block scoped.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.