The Scope Chain, Scope and Lexical Environment in Javascript...

Amit PrajapatiAmit Prajapati
2 min read

Scope of a Variable and Function.

  • We can define a scope where, we can access the variables and function in an Javascript Code.

We will try understand the scope with the help of an example.

var x =10;

function a (){
var x =20;
console.log(x)
}

function b (){
var x =30;
console.log(x)
}
a();
b();
console.log(x)

For the above code we got the below output.

scope-op.PNG

Here we can draw some conclusions regarding the scope chain.

  • We can see that we have consoled x three time in the above program and each time we have got the different results.
  • We have used two functions a and b, both these function have there own local scope, so accordingly we have code the results 20 and 30.
  • We have also got the output 10 which is present in Global scope.

Lexical Environment

We can define Lexical environment as the local memory along with the lexical environment of its parent.

We will try to understand this with the help of an code snipppet.

image-147.png

  • We can see that we are able to dra an output of x+y+z although they are present in their own execution context.
  • In the above example bar function can access the x and y becauuse of the lexical chain.
  • So, while accessing a variable, javascript engine looks for it in the local scope.
  • If it is not present then it checks the lexical environment of the parent.
  • This check goes on untill we reach the Global scope, and finally global scope points to null.
0
Subscribe to my newsletter

Read articles from Amit Prajapati directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Amit Prajapati
Amit Prajapati