Skip to main content

Command Palette

Search for a command to run...

What is Scope and Scope Chaining?

scope and scope chaining

Updated
2 min read
What is Scope and Scope Chaining?
S

Run | Jump | Roar The World

What is Scope?

  • Scope is like a specific area where you can declare and access variables & functions based on needs.

Note: In Js, scope is created whenever only a function gets invoked or called.

There are two types of Scope in JavaScript:

  1. Global Scope

  2. Local Scope

  1. Global Scope:

By default in Js, everything is under global scope. These data can be accessible from anywhere in the code.

//Scope 

let fullName = "Sajib Khan";

function myFunc() {
    console.log(`i am from inner function ${fullName}`)
}

myFunc();

console.log(`I am from outer function ${fullName}`)

  1. Local Scope:

Local scope in JavaScript refers to the context within a function where variables are declared. Variables defined in local scope are only accessible within that specific function and are not visible to the rest of the code outside that function.

//local Scope

let cityName = "Dhaka";

function district() {

    let districtName = "Gazipur"
    console.log(`Sajib from ${districtName}`)
}


console.log(`John from ${cityName}`);

district();

console.log(`Khan also from same location as Sajib ${districtName}`);

What is Scope Chaining?

When a variable is accessed, the JavaScript engine looks for it first in the current scope means its own scope. If the variable is not found, it continues to the outer (enclosing) scope and repeats the process. This chain of nested scopes, where each scope has access to its outer scopes, is known as the "Scope Chain."

We can also describe this process shortly in that child function has access to his parent's components, but the parent function has no access to the child's components. This process is also considered "Lexical Scoping".

// Lexical Scoping or Scope Chaining

function first() {
    let fullName ="Sajib Khan";
    function second() {
        function third() {
            function fourth() {
                console.log("I am a child component");
                console.log(`${fullName} from parent component`);

            }

            fourth();
        }

        third()
    }
    second();
}

first();