Explain the Scope and Scope Chain in JavaScript

the scope defines how and in which part of our code we can access the variables and functions. In simple terms, the scope helps us improve our code’s security and readability. So, we can access the variables and functions only inside its scope but not outside.

We will discuss multiple types of scopes in this tutorial.

Global Scope in JavaScript

The variables and functions defined globally mean outside all blocks and functions with global scope. We can access all variables and functions with the global scope anywhere inside our code.

Syntax

Users can follow the syntax below to define a variable with global scope.

var global = 30;
function func() {
   var b = global; // global variable has a global scope so we can access it inside the function.
}

Here, the global variable global is declared outside of any function, so it has a global scope. It is then accessed inside the function func by declaring a local variable b and assigning it the value of the global variable global.

Local/Function Scope

The local scope is also called the function scope. The variables defined inside the function, have function scope/ local scope. We can’t access the variables outside the function.

Syntax

You can follow the syntax below to understand the local scope of the variable and function −

function func() {
   var local_var = "Hi!";
}
console.log(local_var); // this will raise an error

Here local_var has a function scope inside the func() function, so we can’t access it outside it.

Block Scope

In JavaScript, we can define the block using the two curly braces({ ….. }). The block scope says that whatever variables we define inside the particular block can be accessed only within the block but not outside the block. The variables declared with let and const keywords have block scope.

Syntax

Users can follow the syntax below to understand the block scope of a variable.

{
   let block_var = 6707;
   // block_var accessible here
}

// we can't access the block_var variable here.

Here we can’t access the block_var outside the curly braces as we have defined it inside the particular block.

Note − variables declared with the var keyword don’t have the block scope.

Scope Chain

As the word scope chain suggests, it is a chain of scope. For example, suppose we define the nested function inside the function. In that case, it can have its local scope, and variables declared inside the nested function can’t be accessible in the outer function.

So, we are creating the chain of scopes; that’s why we call it the scope chain.

Syntax

Users can follow the syntax below to learn the scope chain.

function outer() {
   function inner() {
      // inner’s local scope.
      
      // we can access variables defined inside the outer() function as inner is inside the local scope of outer
   }
   
   // variables defined in the inner() function, can’t be accessible here.
}