Hello, Plz Help me

this is an example of ES6 Challenge 1 in JS tutorial.

let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());   // why this is 2?
console.log(i);  // i understood why this is undefined

i don’t understand why 'console.log(printNumTwo()); ’ is 2.

and…

is let declaration in the block statements not hoisted and not on the list of global context??.

and…

when for ?? or if?? statement is run, does JS create a new (local?) context?

sorry my poor question …
haha i’d better learn harder for better questions.

thanks for everybody !

It helps for you to include the link to the page where you got this.

When the function printNumTwo was defined, it ‘remembers’ the value of i that was in context at that time and uses that same value when you call the function later.

1 Like

A function definition has access to the variables in the scopes that contain it as well as its own scope.

2 Likes

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