Scope, Scope chain, and Lexical Environment

codesplash
2 min readApr 20, 2024

--

#7 JavaScript Series

Scope:

It refers to the region of the code where a particular variable or a function is accessible. It defines the context in which variables and functions are declared and accessed.

Types:

Global Scope: variables declared outside any function or block, which are accessible throughout the entire Program.

Local scope: variables declared inside a function or block, which are accessible within that function or block.

let num = 5; // Global Scope variable

function add(a, b) {
let e = 3; // Local scope variable
return a + b + e;
}

console.log(num);
console.log(add(5, 6));

Lexical Environment:

It is the local memory along with the lexical environment of its parent.

A lexical environment is a structure that holds the association between identifiers (like variable and function names) and their corresponding variables or functions within the code. It also keeps track of the scope chain.

Components:

  1. Environment Record: Stores the identifiers and their values.
  2. Reference to outer environment: Links to the lexical environment of the outer scope, forming the scope chain
var a=3; 
function print(){
console.log(a);
}
print(); // Output: 3

Here, a & print are lexically present in the global scope. when print() will be called, print will search for a for console print but, it will not find in its lexical environment, so, it will search to its outer scope i.e. global scope. If in the global scope, there is ‘a’ variable declared it will print that.

Let’s understand lexical environment & scope chain with following code and call stack:

var b=10; // b is on global scope

function a(){ // a is on global scope
c();
function c(){ // c is lexically present inside a
console.log(b);
}
}

a();
call stack

In the call-stack, b anda() are in the global Lexical space. a() has the c() as a part of Lexical environment. c()has nothing in its lexical scope. When a()is called it also calls c() which will find b in the order of following lexical scope
c() → a() → GEC(Global Eexcution Context)

Scope chain:

The scope chain is a series of nested lexical environments. It determines the order in which the JavaScript looks up variables and functions.

Working:
When a variable is accessed, the engine first looks in the current scope’s environment record. If not found, it looks in the outer environment referenced by the scope chain. This process continues until the variable is found or the global scope is reached.

--

--

codesplash

Currently Moulding a New Life Through Coding || Follow me on linkedin codessmasherdeepjyotidas