Home « Previous Next »

Scope Chain

Important

Scope chain is defined by the way program is written within a file

Lets take a look at some examples

"use strict"

function foo() {
  console.log(myVar);
}

function moo() {
  var myVar = 10;
  foo();
}

moo();  // myVar not defined error

The reason why we get this error is because the scope chain is defined lexically - which means, scope chain is defined by the way code is written on a file.

Explanation:

Now lets modified the above snippet slightly.

"use strict"

function moo() {
  var myVar = 10;
  
  function foo() {
    console.log(myVar);
  }
  foo();
}

moo();  // 10

Explanation:

Summary: Variables are resolved in the order in which code is written on a file.

Home « Previous Next »