-1

i do understand that due to lexical scoping, block scopes can access the enclosing scope variables. But what i do not understand is how it really works. ex:

function first(){
  let i=10;
  function second(){
    let j=20;
    console.log(i);
    if(j==20){
    console.log(i);
  } 
  }
  second();
}

the first console.log() get the value of i after its looks up the scope chain in the variable object. But how does the console.log() inside the block get access to variable i as it does not create an execution context and thus no scope chain.

Manishpant
  • 37
  • 1
  • 5

1 Answers1

0

js engine stores hoisted ( by hoisting ) variable and function declarations to the top of particular scope in which that variable or function is declared. Assignment operations aren't hoisted. So engine knows in which scope variable or function is declared.

https://medium.com/@venomnert/how-js-engine-reads-your-code-df3cd36e4192

above article describes how js engine finds variables and some other concepts which can be helpful to understand closures and execution of code.

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 07 '21 at 06:28