Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Scope Chain in Javascript

In this chapter, you will learn about what is the scope chain in Javascript. Each new function in Javascript creates its own environment called scope. The scope holds the variable that it defines and are accessible within the functions. Before understanding the scope chain lets understand different scopes in the Javascript

Scope Chain in Javascript

Global Scope: The variable declared as globally and is available for access throughout your code.
Function Scope: The variable declared inside a function and it can be accessed inside the function itself
Block Scope: The variable declared in a block and those variables are needed in the block.
Lexical scope: In the lexical environment, the Inner function can access the outer variables as well as the variables inside the function. And also get access to the variables that are defined by its parent function. Let’s see the below example to understand the scope properly

var chapter = 'Scope in Javascript';
function Person() {

    var name = 'John in function'; 
    
    function displayName() { 
        var email = 'Email in inner function'
        console.log(chapter);
        console.log(name);
        console.log(email);
    }
    
    displayName();
}
Person();
// output
// Scope in Javascript
// John in function
// Email in inner function

Finally, the displayName function is displaying all the variables, this works with the help of the Scope Chain in Javascript. The displayName can access the variables of Person function that’s why we call this environment as a lexical environment.

One thought on “Scope Chain in Javascript

Comments are closed.