Scope Chain & Lexical environment

Scope Chain & Lexical environment

In this article, we will see scope, scope chain and lexical environment.

start

Let us first see a script and try to guess its output

function a(){
c()
function c(){
console.log(b)
}
}
var b=5;
a();
//output:5

In the above program, the javascript engine will first search for the value of b in the local memory ie function a() when it does not find it moves to global memory.

Now let's do vice-versa of the above example:

function a(){
var b=5;
c()
function c(){
}
}
console.log(b)

When we try to access b from outside the local memory it shows an error.

Screenshot from 2021-06-15 11-23-38.png

Let's see how it happens and why it happens.

Scope

Scope in simple words means where we can access a specific function or variable in our code.

The scope is directly dependent on Lexical environment. Now let us understand the lexical environment with the help of an example:

function a(){
var b=10;
c()
function c(){
console.log(b)
}
}
a();

When we run the above program a call stack is created which contains global execution context and functional execution context.

Screenshot from 2021-06-15 11-53-15.png

Now, the program executed further and the value of b will become 10 and another execution context will be formed of c.

Screenshot from 2021-06-15 11-56-38.png

Whenever an execution context is created a lexical environment is also created. The lexical environment in simple words is nothing but local memory with the lexical environment of a parent.

Lexical means in a hierarchy or sequence. Ex:c function is lexically inside a() function.

Screenshot from 2021-06-15 12-08-03.png

At first, javascript will try to find b inside the local memory when it does not find it there it will go to its reference and then it will go to the lexical environment of its parent. if found there then it will print the value of b or else it will go to the lexical environment of global execution. If found there it will display a value of b or else a go-to reference of the global execution context. The reference of a global execution context is null. We reach null the program stops and the js engine says b is not defined.

Scope chain in simple words the chain of the lexical environment and parent references.

Now let's see the browser demo of all of the above concepts:

Screenshot from 2021-06-15 12-25-49.png

Callstack demo

Screenshot from 2021-06-15 12-27-00.png The lexical environment of the global execution context.

Screenshot from 2021-06-15 12-27-56.png The lexical environment of a. It contains a reference to the parent lexical environment and local memory.

Screenshot from 2021-06-15 12-29-49.png The lexical environment of c. It contains a reference to the parent lexical environment and local memory.

That's it for this article. thanks