How does JavaScript Variable Scope work?



In this tutorial, we will learn how JavaScript variable scope works. In the ES5, there are only two scopes for the variable: Global scope and function scope. In the ES6, we have three scopes available for the variable as added extra scope which is the block scope. However, function scope and block scope come under the local scope category.

Below, we have explained all three scopes with the example.

  • Block Scope
  • Function Scope
  • Global Scope

Block Scope

The JavaScript has three keywords to declare the variable: let, const, and var. The let and const keyword is introduced in the ES6 with the block scope. So, only the variable declared with the let and const keyword provides the block scope but not the variable declared with the var keyword.

Syntax

Users can see the syntax of the block scope as follow.

  • Using the let keyword.
{
   let str = "TutorialsPoint";
   // scope of the str is limited to this block only
}
  • Using the var keyword.
{
   var num = 100;
}
// num can be used outside the block also as it is declared with var keyword.

Example

The below example demonstrates the block scope of the variable.

<!DOCTYPE html>
<html>
<body>
   <h2> Variable scope in JavaScript. </h2>
   <h4> When we use variable declared with var keyword outside the block. </h4>
   <div id="var"> </div>
   <h4> When we use variable declared with let keyword outside the block.</h4>
   <div id="let"></div>
   <script>
      let letOutput = document.getElementById("let");
      let varOutput = document.getElementById("var"); {
         let str = "tutorialsPoint"; // block scope
         var num = 100;
      }
      varOutput.innerHTML = num;
      letOutput.innerHTML = str; // str is undefined error in console.
   </script>
</body>
</html>

In the above output, users can see that for the str variable, the above code gives an error in the console like “str is not defined.” as we are accessing the variable declared with the let keyword outside the block.

Function Scope

When we declare a function in JavaScript, it creates a new scope for every variable declared inside the function. The variables declared with the var, let, and const keyword inside the function all have a function scope, unlike the block scope. The variable declared inside the function, we can’t use them outside the function.

Also, every function creates a new scope when we declare it. So, in different functions, users can declare the variable with the same name using any keyword of let, const, and var.

In this method, we will also see how we can use the block scope inside the function.

Syntax

Users can follow the syntax below to see the function scope's use.

  • Using the var, let, and const keyword.
function demo( ) {
   // all variables have function scope, and can’t be accessed outside the function.
   let x = 10;
   var y = 20;
   const z = 30;
}
function variableDemo ( ) {
   var x = "hello"; // we can declare variable with same name in different function
   {
      let y = 20; // block scope
   }
   // y can’t be accessed here.
}
let a = x; // gives an error as x has only function scope.

Example

In the below example, we have given the demonstration of the function scope.

<!DOCTYPE html>
<html>
<body>
   <h2> Function scope in JavaScript. </h2>
   <h4> values of x, y, z variables in demo() function. </h4>
   <div id="demo"></div>
   <h4> values of x, y, z variables in varialeDemo() function. </h4>
   <div id="vardemo"> </div>
   <script>
      let demoOutput = document.getElementById("demo");
      let vardemoOutput = document.getElementById("vardemo");
      function demo() {
         let x = 10;
         var y = 20;
         const z = 30;
         demoOutput.innerHTML = "x: " + x + ", y: " + y + ", z: " + z;
      }
      function variableDemo() {
         var x = " hello ";
         {
            let y = " hello again! ";
            vardemoOutput.innerHTML = "x: " + x + ", y: " + y;
         }
      }
      demo();
      variableDemo();
   </script>
</body>
</html>

In the above output, users can see that values of x, and y variable inside both the function is different. If we try to access the x, y, or z variable outside the function, it will return an error inside the console of the web browser.

Global Scope

If we declare a variable outside the block or function, it becomes global and we can access it from anywhere inside our program. Users can declare the global variables with all three let, var, and const keywords.

Syntax

Follow the below syntax to make the variable global.

let globalVar = 20;
function demo ( ) {
   let res = globalVar + 20; // we can access global variable inside the function
}
let y = globalVar // we can access the global variable anywhere in the code.

Example

In the below example, we will use the global variable inside the function or anywhere in the code. However, we have used the global variable declared with the let keyword only, but users can use the var and const keyword to declare the global variables.

<html>
<body>
   <h2> Function scope in JavaScript. </h2>
   <h4> When we access the global variable inside the function. </h4>
   <div id="demo"> </div>
   <h4> Accessing the global variable outside the funciton. </h4>
   <div id="vardemo"> </div>
   <script>
      let demoOutput = document.getElementById("demo");
      let vardemoOutput = document.getElementById("vardemo");
      let globalVar = 20;
      function demo() {
         let result = globalVar + 10;
         demoOutput.innerHTML = "The sum of globalVar with 10 is " + result;
      }
      vardemoOutput.innerHTML = globalVar;
      demo();
   </script>
</body>
</html>

In the above output, users can see that when accessing the global variable anywhere in the code, it doesn’t give an error.

Conclusion

This tutorial taught us how variable scope works in JavaScript. If users have any variable which needs to use anywhere in the code, they should make it global. If the need for a variable is inside the particular function, make it a functional scope. Users can declare the variable inside the block to use loops, if-else blocks, or any other code block.

The lifetime of the block scope variable finishes when block execution is finished, and the same happens for the function scope variable. The global scope variable is destroyed only when either you stop the program or close the browser.


Advertisements