Open In App

Understanding variable scopes in JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In JavaScript, there are two types of variable scopes:

  1. Global Scope: Variables declared Globally (outside of any function) have Global Scope and Global variables can be accessed from anywhere in a program. Similar to function scope variables declared with var, let and const are quite similar when declared outside a block.Scope outside the outermost function attached to the window.
  2. Local Scope: Variables declared inside a function become local to the function. Local variables are created when a function starts and deleted when the function is executed. Local variables have Function Scope which means that they can only be accessed from within the function. Inside the function being executed. 

Below examples illustrate the JavaScript Variable Scope:

Example 1: We have a global variable defined in the first line in the global scope. Then we have a local variable defined inside the function fun(). 

javascript




<script>
    let globalLet = "This is a global variable";
 
    function fun() {
      let localLet = "This is a local variable";
 
      console.log(globalLet); // This is a global variable
      console.log(localLet);   // This is a local variable
    }
    fun();
</script>


Output: When we execute the function fun(), the output shows that both global, as well as local variables, are accessible inside the function as we are able to console.log them. This shows that inside the function we have access to both global variables (declared outside the function) and local variables (declared inside the function). Example: Let’s move the console.log statements outside the function and put them just after calling the function. 

javascript




<script>
    let globalLet = "This is a global variable"
 
    function fun() {
      let localLet ="This is a local variable"
 
    }
    fun();
      console.log(globalLet); // This is a global variable
      console.log(localLet); // localLet is not defined
</script>


Output: We are still able to see the value of the global variable, but for local variable console.log throws an error. This is because now the console.log statements are present in global scope where they have access to global variables but cannot access the local variables. Word of caution: Whenever you are declaring variables, always use the prefix let. If you don’t use the let keyword, then the variables are by default created in the global scope. For instance, in the above example.

Example: let’s just remove the keyword let before the declaration of localLet. 

javascript




<script>
    let globalLet = "This is a global variable";;
 
    function fun() {
       localLet = "This is a local variable";
    }
 
    fun();
      console.log(globalLet); // This is a global variable
      console.log(localLet); // This is a local variable
</script>
"


Output: We are now able to console.log the local variable as well because the localLet was created in the global scope as we missed the keyword let while declaring it. What really happened is that as we didn’t use the let keyword, JavaScript first searched the localLet in local scope, then in the global scope. As there was no existing global variable by that name, so it created a new global variable. Example: One of the most asked questions in interviews is the scenario where the global as well as local variable has the same name. Let’s see what happens then. 

javascript




<script>
    let globalLet = "This is a global variable"
 
    function fun() {
      let globalLet = "This is a local variable"
    }
    fun();
    console.log(globalLet); // This is a global variable
</script>


Output: In this example, we have declared a local as well as global variable “globalLet”. What matters here is the scope in which we are accessing it. In this example, we are accessing it in global scope, so it will output the global variable as a local variable is not present in its scope. Example: Let’s move the console.log statement inside the function fun(). 

javascript




<script>
    let globalLet = "This is a global variable";
 
    function fun() {
      let globalLet = "This is a local variable";
      console.log(globalLet); // This is a local variable
    }
    fun();
</script>


Output: Inside the function fun(), both the local as well as global variables are accessible. But when we console.log the variable globalLet, firstly JavaScript tries to find a local variable in the current scope. It finds the local variable and outputs it. Otherwise, it would have to search for the variable “globalLet” in the outer scope (which in this case is global scope). Example: What if we want to access the global variable instead of the local one here? Well, the window object comes to our rescue. All the global variables declared using the “var” keyword or without using any keyword are attached to the window object and thus we can access the global variable name as shown in the example below. 

javascript




<script>
    let globalLet = "This is a global variable";
 
    function fun() {
      let globalLet = "This is a local variable";
      console.log(window.globalLet); // This is a global variable
    }
    fun();
</script>


Output: Example: After discussing scopes in JavaScript, guessing the output of the below code fragments should be a cakewalk. 

javascript




<script>
    function fun(){
        function fun2(){
             i = 100;
        }
        fun2();
        console.log(i); // 100
    }
    fun();
<script>


Output: In this example, as we didn’t use the keyword let, the variable “i” was assumed to be declared in the global scope, and thus the output was 100. Example:

javascript




<script>
    function fun(){
        function fun2(){
            let i = 100;
        }
        fun2();
        console.log(i); // i is not defined
    }
    fun();
</script>


Output: In this example, “i” became a local variable and thus was not accessible outside the scope of that functionIn the first example, as we didn’t use the keyword let, the variable “i” was assumed to be declared in the global scope, and thus the output was 100. In the second example, “i” became a local variable and thus was not accessible outside the scope of that function.

Example:

javascript




<script>
    function fun(){
        if(true){
            let i = 100;
        }
        console.log(i); // i is not defined
    }
    fun();
</script>


Output: After ES2015, we started using let instead of var for declaring variables, and also now the if block is also counted as a block scope, hence in the above example we get an error instead of the value 100. In earlier versions If we change the let to var we will get 100 as output as “if..else” block was not considered a block scope earlier, only functions were considered block scope.

Also, the const keyword has the same scope as the let keyword and is also a block scope.



Last Updated : 24 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads