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.


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


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

thank you for your kindness!
i thought that a new lexical environment is created when a function is called.
you mean that for? or if? statement creates new lexical environment when for? or if? statement is run?

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