Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Why is a JavaScript scope chain defined at compile time rather than execution time?

The below example will throw a ReferenceError because x is not defined. I know that this is because there is no implicit variable declaration for x within bar or the global scope.

What is going on with the JavaScript compiler though that means the scope chain only gets defined at compilation time, instead of when the function is executed? Why does bar not have access to x when it is called within foo?

function foo() {
  var x = "y"

  console.log(bar())
}

function bar() {
  return x
}

foo()

Comments