Learnitweb

Lexical scope in JavaScript

A lexical scope is a scope that is defined at lexing time. In other words, lexical scope is based on where variables and blocks of scope are written.

Let us understand this with the help of an example.

function outerFunction(x) {
  var y = x * 3;
  function innerFunction(z) {
    console.log(x, y, z);
  }
  innerFunction(y * 3);
}
outerFunction(5); // 5, 15, 45

There are three nested blocks in this code.

  1. The global scope, which has one identifier outerFunction.
  2. The scope of outerFunction, which has 3 identifiers, x, y and innerFunction.
  3. The scope of innerFunction, which has one identifier, z.

The scope of outerFunction and innerFunction are based on where you have written these functions. For example, the scope of innerFunction is inside scope of outerFunction because that is how you have decided to write it.

Scope look-up

Scope look-up starts at the innermost scope and continues search upward/outward until the first match. Once a match is found, search is stopped. Let us understand this statement from our previous code.

  1. console.log(x, y, z) is executed and variables are searched in scope of innerFunction.
  2. The variables if not found are searched in the scope of outerFunction.
  3. If the variables are not found in outerFunction then they are searched in global scope.

If at any step, a match (first) is found, the search for that variable is stopped.