Search code examples
javascriptscopeexecutioncontext

Javascript - scope chain


I read a number of articles about the javascript scope chain and I thought I had a decent understanding of it. However, a very simple exercise made me realize I do not yet understand it at all.

I created the following code.

function foo () {
  var b = 2;

  bar()

} 

function bar () {
  console.log(b);

}

foo();

This code gives a reference error. However, I assumed that it would still print out 2. My reasoning was the following:

  • Function declaration of foo and bar.
  • Foo is executed, this creates a new execution context. Foo has internal property [[Scope] set to global.
  • var b is hoisted.
  • var b is assigned 2.
  • bar is executed inside of the foo execution context. Therefore, I assumed the internal property [[Scope]] of the bar function would be set to foo.
  • b is not defined in function bar, therefore the scopechain is looked up and finds the value b = 2.
  • console.log(2);

My reasoning is based on that I understand that the [[Scope]] internal property of function X is set to the execution context that is running at the time function X is executed. Not based on where function X is declared.


Solution

  • b is defined in foo's scope.

    bar is called from foo's scope, yes, but it's defined outside of foo's scope. This means that bar can not access b.

    As an image can often help:

    enter image description here

    Consider each red square to be a "scope". foo and bar share the outer scope, but they can't access each other's inner scope.