The Wayback Machine - http://web.archive.org/web/20240930221033/https://www.geeksforgeeks.org/understanding-variable-scopes-in-javascript/
Open In App

Understanding variable scopes in JavaScript

Last Updated : 24 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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). ImageExample: 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. ImageWord 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. ImageExample: 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. ImageExample: 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). ImageExample: 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: Image 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. Image 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 functionImageIn 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: ImageAfter 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.



Similar Reads

All about Functions and Scopes in JavaScript
In this article, we will cover all the basic concepts of JS functions, callbacks, scopes, closures in-depth which would help you to - understand different types of function declarations.make better use of functions.understand how different scopes and scope chain works in JS.learn about closures and how to use them.We will understand all these conce
10 min read
Explain Different Types of Scopes in JavaScript ?
Scope refers to the environment in which a variable or a function is declared and accessible. It means the environment in which the variable is visible, can be accessed and changes can be made to it. It is of three types in JavaScript. Functional Scope: This scope is mainly contained by the variables that are declared inside a function. These varia
1 min read
What are the different scopes of variables in PHP ?
Variable Scopes: The scope of a variable is defined as its extent in the program within which it can be accessed, i.e. the scope of a variable is the portion of the program within which it is visible or can be accessed. Depending on the scopes, PHP has three variable scopes. Local variables: The variables declared within a function are called local
3 min read
variable === undefined vs. typeof variable === “undefined” in JavaScript
Undefined comes into the picture when any variable is defined already but not has been assigned any value. Undefined is not a keyword. A function can also be undefined when it doesn't have the value returned. There are two ways to determine if a variable is not defined, Value and type. var geeks; alert ( geeks === undefined) It's so clear that you
2 min read
Understanding Templates Variable in Angular
Template variables in Angular allow us to use the data from one part of the template to another part of the same template. There are various use cases where these template variables come in handy. For example, responding to the user input or responding to the form submission. In this article, we'll explore what are template variables and how to use
4 min read
JavaScript Course Understanding Code Structure in JavaScript
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. The 'type' attribute was the most important attribute of <script> tag. However, it is no
4 min read
Understanding basic JavaScript code
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. <script> tags can be put between the <head> and </head> tags or between <b
3 min read
Understanding the Prototype Chain in JavaScript
When you started learning to program, you would have encountered the term object-oriented programming. Here we discover what it meant and you acknowledged that it is for grouping data into “objects” with attributes. The keyword that creates these objects in many programming languages is class. You define a category with a constructor and a number o
2 min read
Understanding the Async in JavaScript
Definition: Async is a short form for “asynchronous”. Synchronous means executing statements one after the other which implies the next statement will get executed only after the previous statement is executed completely. Whereas in Asynchronous calls the next statement gets executed without even waiting for the previous one's execution. JavaScript
4 min read
Understanding the Difference between Pure and Impure Functions in JavaScript
In this article, we will see the concepts of pure and impure functions in JavaScript, along with understanding their differences, & basic implementation for a better understanding of the concepts. Pure Functions: This function always returns the same output as given the same input parameters. Pure functions only depend on their input parameters
5 min read
Understanding Callbacks and Callback Hell in JavaScript
In JavaScript, a callback is a function passed to another function to execute after an asynchronous operation completes. Callback hell refers to the problematic situation where multiple nested callbacks create a "pyramid of doom," making the code difficult to read, debug, and maintain. CallbackA callback is a function passed as an argument to anoth
4 min read
JavaScript Check the existence of variable
JavaScript has a built-in function to check whether a variable is defined/initialized or undefined. To do this, we will use the typeof operator. The typeof operator will return undefined if the variable is not initialized and the operator will return null if the variable is left blank intentionally.Note: The typeof operator will check whether a var
2 min read
How to check a variable is of function type using JavaScript ?
A function in JavaScript is the set of statements used to perform a specific task. A function can be either a named one or an anonymous one. The set of statements inside a function is executed when the function is invoked or called. A function can be assigned to a variable or passed to a method. var gfg = function(){/* A set of statements */}; Here
3 min read
JavaScript Set object key by variable
In order to set an object's key by variable, here are few steps to follow. Steps: First make a variable.Then make a object.Assign that variable a value. Example-1: This example sets the object key by variable key and then inserts {"GFG_key":"GFG_Val"} object to a array. C/C++ Code <h1 style="color:green;"> GeeksForGeeks </h1>
2 min read
How to change the value of a global variable inside of a function using JavaScript ?
Pre-requisite: Global and Local variables in JavaScript Local Scope: Variables that are declared inside a function is called local variables and these are accessed only inside the function. Local variables are deleted when the function is completed. Global Scope: Global variables can be accessed from inside and outside the function. They are delete
2 min read
How to use a variable for a key in a JavaScript object literal?
In ES5 and earlier, you could not use a variable as a property name inside an object literal. The only option you had was to create the object literal, assign the variable property name with value and pass the resulting object to the animate method. ES6 defines 'ComputedPropertyName' as part of the grammar for object literals, which helps use a var
1 min read
How to load the contents of a text file into a JavaScript variable?
In this article, we will examine how to read the contents of any text file that exists on your computer into a variable using JavaScript. The following are a few basic pointers that everybody should brush through before looking at the code: Event listeners: These are predefined functions that exist in JavaScript. They take two arguments, the first
3 min read
How to create a variable using a user-defined name in JavaScript ?
In this article, we will learn to create a variable using the user-defined name in JavaScript. Variables in JavaScript: Basically, it is a container that holds reusable data in JavaScript. The variable's value can be changed during program execution and should be declared before using it. Before ES6 declares a variable, we just use the var keyword
2 min read
JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization
This JavaScript exception can't access the lexical declaration `variable' before initialization occurs if a lexical variable has been accessed before initialization. This could happen inside any block statement when let or const declarations are accessed when they are undefined. Message: ReferenceError: Use before declaration (Edge) ReferenceError:
2 min read
JavaScript SyntaxError "variable" is a reserved identifier
This JavaScript exception variable is a reserved identifier occurs if the reserved keywords are used as identifiers. Message: SyntaxError: The use of a future reserved word for an identifier is invalid (Edge) SyntaxError: "x" is a reserved identifier (Firefox) SyntaxError: Unexpected reserved word (Chrome) Error Type: SyntaxError What happened? Whe
1 min read
JavaScript ReferenceError - Assignment to undeclared variable
This JavaScript exception Assignment to undeclared variable occurs in strict-mode If the value has been assigned to an undeclared variable. Message: ReferenceError: assignment to undeclared variable "x" (Firefox) ReferenceError: "x" is not defined (Chrome) ReferenceError: Variable undefined in strict mode (Edge) Error Type: ReferenceError Cause of
2 min read
JavaScript ReferenceError - variable is not defined
This JavaScript exception variable is not defined and occurs if there is a non-existent variable that is referenced somewhere. Message: ReferenceError: "x" is not defined Error Type: ReferenceError Cause of Error: There is a non-existent variable that is referenced somewhere in the script. That variable has to be declared or make sure the variable
1 min read
How to add a property to a JavaScript object using a variable as the name?
In JavaScript, you can dynamically add a property to an object using a variable as the name. This allows you to create flexible and dynamic objects based on runtime values, enhancing code reusability and adaptability. There are several methods that can be used to add a property to a JavaScript object using a variable as the name. Using Dot Notation
2 min read
JavaScript TypeError - Variable "x" redeclares argument
This JavaScript exception variable redeclares argument occurs in strict-mode only and if the variable name which is also function parameter has been redeclared with the var keyword. Message: TypeError: variable "x" redeclares argument (Firefox) Error Type: TypeError Cause of the Error: A variable which is the parameter of the function has been re-d
1 min read
What happen when we directly assign the variable without declaring it in JavaScript ?
JavaScript has two scopes which are the local scope and global scope and when we directly assign a variable without declaring, it becomes a global property of the window object. The window is the object of the browser. It is not the object of JavaScript. It is automatically created by the browser and it can be accessed from anywhere on the web page
2 min read
How to create a private variable in JavaScript ?
In this article, we will try to understand how we could create private variables in JavaScript. Let us first understand what are the ways through which we may declare the variables generally in JavaScript. Syntax: By using the following syntaxes we could declare our variables in JavaScript. var variable_name = value Also, another syntax that we cou
3 min read
What are the variable naming conventions in JavaScript ?
When we name variables in javascript, we've to follow certain rules. Each variable should have a name that appropriately identifies it. Your JavaScript code gets easier to comprehend and work with when you use suitable variable names. It's critical to name variables correctly. For example Constants and global variables are always written in upperca
2 min read
How to check the type of a variable or object in JavaScript ?
In this article, How to Check the Type of a Variable or Object in JavaScript? In JavaScript, the typeof operator is used to determine the typeof an object or variable. JavaScript, on the other hand, is a dynamically typed (or weakly typed) language. This indicates that a variable can have any type of value. The type of the value assigned to a varia
2 min read
Scope : Variable Masking in JavaScript
In this article, we will learn about Variable Masking which is also known as Variable Shadowing i.e. a variable with the same name will shadow the variable in the outer scope. When a variable is masked, the masked variable is completely inaccessible using that variable name. The scope is hierarchical thus we can enter new scope without hampering th
3 min read
Why JavaScript Variable Starts with a Dollar Sign ?
In JavaScript, it is common to see variables that start with a dollar sign ($). This convention is not required by the language, but it is often used by developers to indicate that a variable is a jQuery object or to distinguish it from other types of variables. In JavaScript, variable names can only contain letters, numbers, and underscores (_), a
3 min read