Scope & Lexical Environment in JavaScript

Scope in JavaScript is directly related to lexical environment.

Scope of a variable referes to where all the variable can be accessed.

Whenever an execution context is created, a lexical environment is also created.

Lexical Environment is the local memory and the lexical environment of its parent. Local memory refers to the memory component of the execution context.

Lexical basically means hierarchical.

If the above lines did not make any sense, don't worry. Let's simplify this.

Let's say a variable(var) is declared in the global space. This variable can be accessed anywhere in the entire program. This means that a variable declared in the parent is accessible to its child.

Now we have another variable which is declared inside a function. This variable can be accessed only within the function. This variable cannot be accessed beyond the function's scope.

function a() {

var b = 10;

c();

function c() {

console.log(b);

}

}

a();

Output

10

Explanation: Scope is directly related to lexical environment and lexical environment is the local memory plus the lexical environment of its parent.

function a() {

var b = 10;

}

console.log(b);

Output

Uncaught ReferenceError: b is not defined at <anonymous>

[anonymous is the global execution context]

JavaScript will first search for a variable in the local memory. If not found it searches for the variable in the variables' parent's local memory, and so on.

function a() {

var b = 10;

console.log(b);

}

var b = 20;

a();

console.log(b);

Output

10

20

Explanation: When JS encounters log of b inside function a, it first searches for b in local memory which it finds to be 10.

function a() {

console.log(b);

}

var b = 20;

a();

console.log(b);

Output

20

20

Here, JS couldn't find variable b inside function a, so it searches for b in a's parent which is the global space here.

This chain formed as a result of searching a variable in lexical environment is called scope chain.