Explain the Scope and Scope Chain in JavaScript


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.

Example

We have defined the global variable with the global scope in this example. We are accessing it inside the function named func() and returning its value from the function.

In the output, we can observe that the func() function returns 20, which is the value of the global variable.

<html>
   <body>
      <h2> Defining a variable with <i> global </i> scope </h2>
      <div id = "output"> </div>
      <script>
         let output = document.getElementById("output");
         var global = 20;
         function func() {
            return global;
         }
         output.innerHTML += "The value of variable named global: " + func();
      </script>
   </body>
</html>

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.

Example

In this example, we have created the func() function. Inside the func() function, we have defined the local_var variable with a local scope, which means we can access it only inside the func() function. We can see that if we try to access the local_var outside the func() function, it raises an error as local_var is undefined. To see this error you need to open the console.

<html>
   <body>
      <h2>Defining a variable with <i> function </i> scope</h2>
      <div id = "output"> </div>
      <script>
         let output = document.getElementById("output");
         function func() {
            let local_var = 20;
            output.innerHTML += "The value of local_var inside fucntion: " + local_var + "<br/>";
         }
         func();
         // the local_var can't be accessed here
         output.innerHTML += "The value of local_var outside fucntion: " +local_var+ "<br/>";
      </script>
   </body>
<html>

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.

Example

In this example, we have defined a block using the curly braces and defined a variable num. We try to access this valiable inside and outside the block. You can observe that we can’t access num outside the curly braces as we have defined it inside the block.

<html>
   <body>
      <h2>Defining the variable with <i> block </i> scope </h2>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
         {
            const num = 200;
            output.innerHTML += "Value of num inside the block: " + num + "<br>";
         }
         // num is accessible here - outside the block
         output.innerHTML += "value of num outside the block: " + num + "<br>";
      </script>
   </body>
</html>

Lexical Scope

The lexical scope is the same as the static scope. In JavaScript, when we execute the nested function and try to access any variable inside the nested function, it finds the variable first inside the local context. If it doesn’t find the variable in the local context of the nested function, it tries to find in the parent context from where the function is executed, and so on. At last, if it doesn’t find the variable in the global context, it considers it undefined.

Syntax

Users can follow the syntax below to understand the lexical scope.

var parent_var = 343;
var test = function () {
   console.log(parent_var);
};
test();

In the above syntax, we have accessed the parent_var from the scope where the function is executed. As function log() will not find parent_var in the local scope, it will try to find in the scope from where the function is invoked, which is the global scope.

Example

In this example, we defined the test() function and nested() function inside. Also, we are accessing the global_var and parent_var inside the nested() function. As JavaScript will not find both variables in the local context, it will look in the execution context of the nested() function first and then in the execution context of the test() function.

<html>
   <body>
      <h2>Defining the variables with <i> lexical </i> scope</h2>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
         var global_var = 576505;
         var test = function () {
            var parent_var = 343;
            var nested = function () {
               output.innerHTML += "The value of parent_var: " + parent_var + "<br/>";
               output.innerHTML += "The value of global_var: " + global_var + "<br/>";
            };
            nested();
         };
         test();
      </script>
   </body>
</html>

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.
}

Example

In this example, the inner() function is inside the scope of the outer() function, which means we can’t call the inner() function outside the outer() function. The inner() function creates the scope chain inside the outer() function.

<html>
   <body>
      <h2>Scope Chain in JavaScript </i></h2>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
         function outer() {
            var emp_name = "Shubham!";
            function inner() {
               var age = 22;
               output.innerHTML += ("The value of the emp_name is " + emp_name) +"<br/>";
               output.innerHTML += "The value of the age is " + age;
            }
            inner();
            
            // age can't be accessible here as it is the local scope of inner
         }
         outer();
      </script>
   </body>
</html>

In this tutorial, we dicussed the scope and scope chain in JavaScript. We discussed globle, local/ function, block and lexical scopes. And in the last section we understood how scope chain works in Javascript.

Updated on: 05-Jan-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements