Scope , Scope Chain and lexical Environment

 “Scope of JavaScript is directly related to lexical environment”

function a(){
    console.log(b);
 }
 var b = 'shreyash'
 a()
    supposed we create a function “a” inside it “console log b” and declare the “b” variable outside of function and call it a(). what’s will happened?.
    first of all JavaScript engine go to inside of function and try to find this “b” inside the local memory of this “a()” execution context and it won’t be there. because the “b” declare outside to function. so, JavaScript engine find “b” in globally means Global execution context and it is here.
shreyash
but,
function a(){
    console.log(b);
 }
 a()
 var b = 'shreyash'
This time function will execute and return undefined. Because after the calling function, variable b is declared.

Scope
“ scope means a specific variable or function in our code.”
function a(){
    console.log(b)
 }
 var b = 10;
 a();
In this case, the scope of the variable “b” is Global. means we can access it inside a function or outside a function.
function a(){
    var b = 10;
}
console.log(b);
a();
In this case, the scope of the variable “b” is block level scope. means it limited only for this function, we can not access it outside of function.

Lexical Environment
    Whenever execution context is created is lexical environment is also created. lexical environment is the local memory along with the lexical environment of its parent.
function a(){
    function c(){
         console.log('this is c function')}
    c();
 }
 a()
See example, we declare a function ‘a’ and inside it we declare another “c” function, so function “a” is a parent of “c” so, the “c” function lexically inside “a” function that means in order, in hierarchy. and also ‘a” is lexically inside global scope, so this is known as lexical.

Scope Chain

    In this call stack, this arrow refer to parent of the lexical function. this is chain like structure and last is null means not parent and nothing any more this is called as Scope chain
    In short, this chain of all this lexical environment and the parent reference this known as scope chain.

local memory + reference to lexical env. of parent