var greeting = 'Hello World!';function greet() {
console.log(greeting);
}
// Prints 'Hello World!'
greet();
function greet() {
var greeting = 'Hello World!';
console.log(greeting);
}// Prints 'Hello World!'
greet();
console.log(greeting);
{
let greeting = 'Hello World!';
var lang = 'English';
console.log(greeting); // Prints 'Hello World!'
}// Prints 'English'
console.log(lang);// Uncaught ReferenceError: greeting is not defined
console.log(greeting);
Diagram showing scope chain and lexical scope

Let understand this with an code –
var a = "himanshu";
functiondemo1(){
var a = "shekhar";
console.log(a);
demo2();
functiondemo2(){
console.log(a);
}
}
demo1();
Taking the above example , the js pointer , does not directly jump to global space and find the variable a , instead it follow as specific path –
thus forming a chain , known as scope chain.
demo2() scope ---> demo1() scope ---> global scope
Also know as static scope.
Lexical environment of a variable is a combination of -
- local memory and
- parent lexical scope
Lets understand this with an code example –
var a = "himanshu";
functiondemo1(){
var a = "shekhar";
console.log(a);
demo2();
functiondemo2(){
console.log(a);
}}
const fullName = "Jhon";
function profile() {
const fullName = "Tobi";
console.log(fullName);
function sayName() {
console.log(fullName);
function writeName() {
const fullName = "Shah";
console.log(fullName);
}
writeName();
}
sayName();
}
profile();
function showLastName() {
const lastName = "Sofela";
return lastName;
}
// Define another function:
function displayFullName() {
const fullName = "Oluwatobi " + showLastName();
return fullName;
}
// Invoke displayFullName():
console.log(displayFullName());
Advertisement