Complete Detail about Scope, and Lexical Environment , Scope Chaining  with Code Snippets

Complete Detail about Scope, and Lexical Environment , Scope Chaining with Code Snippets

ยท

6 min read

Scope:

Scope means accessing a particular variable and a function in our code. In other words, scope determines the accessibility and visibility of a variable/function.

Types Of Scopes:

Global Scope:

Variables declared outside the function are called global scope variables. and these variables can be accessed from anywhere in the program

Example:
--------
var username = 'deepak kumar'
let surname = 'nayak'
const location = 'India'

function displayDetails(){
  console.log(username) // can be accessibile here
  console.log(surname)  // can be accessibile here
  console.log(location) // can be accessibile here

  function displayData(){
    console.log(`accessing it from inner function ${location}`)
  }
  displayData()
}

displayDetails()

console.log(username) // can be accessible here also 
console.log(surname)  // can be accessible here also

Note: so I can access these inside the function as well as outside the function.

Local Scope:

Variables that are defined inside the function are known as Local Scope variables and they are accessible only inside that function not outside the function.

console.log(username) //not accessible here

function displayDetails(){
  var username = "deepak"
  console.log(username)  // we can access it here
}
console.log(username)  // not accessible here

Block Scope

In Javascript, the block scope concept came into existence after the es6 was introduced into javascript. the let and const behave as a block scope I mean the two keywords let and const provide the block scope in javascript

In block scope, the variables which are declared inside the block cannot be accessed outside the block.

function displayNumbers(){
  if (true){
    var a = 30 
    let b = 40
    const c = 50
  }
  console.log(a) // a can be accessible because here a is not a block scope
  console.log(b) // cannot be accessed here as it acts as a block scope
  console.log(c) // cannot be accessed here as it acts as a block scope
}

displayNumbers()

Note: The variables which are declared with var are not considered as block scope but the variables declared with let and const are considered as a block-scope

Example for Scope:

var userName = 'deepak'

function displayDetails(){
  console.log(userName)
}

displayDetails()

so from the above example will I be able to access the userName. ? , So yes I can access it, I have declared it in the global scope. And anything I am declaring in the global scope I can access anywhere in the program.

In The above program first of all it will try to find out the username inside the local memory space which means inside the displayDetails function ( local memory of displayDetails execution context ) which is not available but still it will print out the value

Lexical Environment:

Before getting into Lexical Environment let's understand what lexical is with the help of an Example:

function display_name(){
    let name = "deepak kumar nayak"
    console.log(name)
}
display_name()

Lexical means where it is being positioned. Look into the code snippet if someone ask's you where the variable name โฌ… is lexically positioned, and the answer will be it is lexically present/positioned inside the function called display_name ๐Ÿ‘

Whenever an execution context is created a lexical environment is also created Lexical Environment is the local memory along with the lexical environment of its parent.

if I look into the above example what is the memory comprised of I mean what is present inside the display_name()

  1. variable name

  2. console.log(name)

Example Two:

function display(){
  let username = "deepak"
  function displayName(){
    console.log(username)
  }
  displayName()

}

display()

so as soon as the program will execute a global execution context is created and it is been pushed into callstack.

as we know it consists of the memory part and the code part though we have run this program now it will try to assign the value to the global variables and function and in this example display is in the global space so it will try to assign value to display, and here display will point out to the whole function

now it will invoke the function so invoking of function will again lead to the creation of a brand new execution context, dividing it into two parts memory and code part.

in this part username will be set to undefined and the displayName function will be pointing towards the whole function

now when the code will execute I mean when the code execution phase will start at that time the username will be replaced with its original value which is ("deepak")

and now just look at the code again a function will be called which is known as displayName function, so again a brand new execution context will be created and it is again divided into two parts. here I am only consoling the value of username.

Scope Chain:

so this is how the stack looks, displayName function is lexically sitting inside the display function. and display function is lexically sitting inside the global scope.

displayName is pointing to the lexical environment of its parent so in this case its parent is display function, because displayName function is lexically inside the display function so that means it will get access to the lexical environment of display function.

display function points to the lexical environment of its parent, known as global execution context.

when I am trying to access the value of the username inside the displayName function first of all it will try to search inside the local memory of the displayName function eventually I haven't defined anything called username inside the displayName function.

so now it will try to find out inside the lexical environment of its parent which is inside the display function and in the display function it finds out the username and prints out in the console.

suppose if username was not there inside the display function then it would have gone to the lexical environment of the display function parent which is global

now it will go and find inside the global and if it is not present inside global also then we will get an error as ReferenceError: username is not defined.

So what we are doing here we are searching the value of username and how we are searching from its local memory, If it is not present in the local memory then it will search in the parent lexical environment this mechanism of finding a variable from one lexical environment to other is known as Scope Chain.

Another Example For Scope Chain

let userName = "deepak"

function displayData(){
    let gmail = "deepak@gmail.com";
    let courseTaken = 1;
    function courseName(){
        let courseName = 'fullstack javascript 2.0'
        function displayCourseName(){
            console.log(`${courseName} ${userName}`)
        }
        displayCourseName()
    }
    courseName()
}
displayData()

In the second example Look at the function displaycoursename here I am trying to access the username and coursename.

  • here also 1st I will try to find in its local memory which is inside the displaycoursename so the username is not present in the local memory.

  • now it will try to find out inside the parent lexical environment and there also username is not present.

  • then again it will try to find out in the parent lexical environment of coursename which is displayData there also it is not present.

  • now it will find out in the lexical environment of display data which is global, in the global.

  • This mechanism of finding the varaible from one lexical environment to anoher is called Scope Chain.

the scope chain is nothing but the chain of the lexical environment along with its parent references.

Important Points:

  • Scope determines the accessibility and visibility of a function and variable.

  • the lexical environment is created whenever an execution context is created.

  • the lexical environment is the local memory and lexical environment of its parent.

  • the scope chain is nothing but the chain of the lexical environment along with its parent references.

ย