JavaScript Scope Chain

In JavaScript, variable scope may be thought of as a chain. When searching for a variable definition, the JavaScript engine inspects first the local execution context object (ECO). (See execution context).Should the definition not be found, the engine moves up the scope chain to the execution context it was created in and searches that ECO, and so on until it locates the definition or reaches the global scope.

Example 1. foo defined in each calling scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// foo defined in the global scope
var foo = 'foo';

// Logs 'foo'
// Scope chain: global
// Closes match in scope chain: global foo
console.log(foo);

function bar() {
  var foo = 'foo bar';

  // Logs 'foo bar'
  // Scope chain: global - bar()
  // Closest match in scope chain: the foo defined in bar().
  console.log(foo);
  function baz() {
    var foo;

    // Logs 'undefined'
    // Scope chain: global - bar() - baz()
    // Closest match in scope chain: the foo defined in baz();
    console.log(foo);
  }
  baz();
}

bar();

Above, the variable, foo, is requested and defined in three scopes. Since its defined in each scope, the engine only needs to search one ECO, the EC in which foo is defined.

Example 2. foo defined only in one scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var foo = 'foo';

// Logs 'foo'
// Scope chain: global
// Closes match in scope chain: global foo
console.log(foo);

function bar() {
  // Logs 'foo'
  // Scope chain: global - bar()
  // Closest match in scope chain: global foo
  console.log(foo);

  function baz() {
    // Logs 'foo'
    // Scope chain: global -> bar() -> baz()
    // Closest match in scope chain: global foo
    console.log(foo);
  }

  baz();
}
bar(); // Logs 'foo' two times

In conclusion, we must remember that when a variable is requested, it may return from anywhere in the scope chain.

Reference:
Mikowski, Michael S., and Josh C. Powell. Single Page Web Applications: JavaScript End-to-end. Shelter Island, NY: Manning, 2013. Print.