0

Very simple question that struggles my mind. Here I have a function that calls another function

function fn2() {
  console.log(myName);
}

function fn1() {
  var myName = "John";
  fn2();
  return 15;
}
fn1();

From what I know so far, JavaScript creates a new execution context for each function invocation. So the order should be global execution context -> fn1 -> fn2. And when fn2 tries to access a variable that is not defines in its scope, it look in the scope chain to see if it is defined there. Since fn2 doesnt have local variable 'myName', it should check to see if it is defined it its outer scope, which is fn1 and the variable is indeed defined there. However when i run this code i receive an error that myName is not defined. Why is that the case.

  • 1
    myName is ONLY visible inside fn1 - that is how variable scoping works in JS - there is no "outer scope" inside the function but the global scope – mplungjan Aug 21 '21 at 11:32
  • then what is the use of the scope chain? – Evgeni Kanchev Aug 21 '21 at 11:38
  • https://stackoverflow.com/questions/1484143/scope-chain-in-javascript#:~:text=Scope%20chain%20in%20javascript%20is,browser%20(%20global%20in%20NodeJS%20). – mplungjan Aug 21 '21 at 11:44

0 Answers0