Skip to content
Related Articles
Open in App
Not now

Related Articles

Global and Local variables in JavaScript

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 15 Dec, 2022
Improve Article
Save Article

Global Variable: These are variables that are defined in global scope i.e. outside of functions. These variables have global scope, so they can be accessed by any function directly. In the case of global scope variables, the keyword they are declared with does not matter they all act the same. A variable declared without a keyword is also considered global even though it is declared in the function.

Local Variable: When you use JavaScript, local variables are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them. Accessing them outside the function will throw an error

How to use variables:

  • The scope of a variable or function determines what code has access to it.
  • Variables that are created inside a function are local variables, and local variables and local variables can only be referred to by the code within the function.
  • Variables created outside of functions are global variables, and the code in all functions has access to all global variables.
  • If you forget to code the var keyword in a variable declaration, the JavaScript engine assumes that the variable is global. This can cause debugging problems.
  • In general, it’s better to pass local variables from one function to another as parameters than it is to use global variables. That will make your code easier to understand with less chance of errors.

Example 1: In this example, we will declare variables in the global scope so that they can be accessed anywhere in the program.

HTML




<h1 style="color: green">
    GeeksforGeeks
</h1>
<p>
    A GLOBAL variable can be accessed from any script or function.
</p>
<p id="geeks"></p>
<p id="Geeks"></p>
<script>
    var petName = 'Rocky' // Global variable
    myFunction()
      
    function myFunction() {
        fruit = 'apple'; // Considered global
            document.getElementById('geeks').innerHTML =
                      typeof petName + 
                '- ' + 
                'My pet name is ' + 
                petName
         }
      
    document.getElementById('Geeks').innerHTML +=
            typeof petName +
            '- ' +
            'My pet name is ' +
            petName +
            '<br> Fruit name is ' +
            fruit
</script>

Output:

 

Explanation: We can see that the variable petName is declared in the global scope and is easily accessed inside functions. Also, the fruit was declared inside the function without any keyword so it was considered global and was accessible inside another function. 

Example 2: In this example, we will declare variables in the local scope and try to access them at different scopes.

HTML




<h1 style="color:green;">GeeksforGeeks</h1>
  
<p id="Geeks">
    Pet Name according to first function: 
</p>
<p id="geeks">
    Pet Name according to second function: 
</p>
<p id="out">
    Pet Name outside function: 
</p>
<script>
    myfunction();
    anotherFunc();
    var petName;
    function myfunction() {
        var petName = "Sizzer"; // local variable
        document.getElementById("Geeks").innerHTML += petName;
    }
    function anotherFunc() {
        var petName = "Tom"; // local variable
        document.getElementById("geeks").innerHTML += petName;
    }
    document.getElementById("out").innerHTML += petName;
</script>

 Output:

 

Explanation: We can see that the variable petName is declared in global scope but not initialized. Also, the functions are accessing the inner variable where each function has its own value for the variable petName.

Where to use which variable:

  • Although it may seem easier to use global variables than to pass data to a function and return data from it, global variables often create problems. That’s because any function can modify a global variable, and it’s all too easy to misspell a variable name or modify the wrong variable, especially in large applications. That, in turn, can create debugging problems.
  • In contrast, the use of local variables reduces the likelihood of naming conflicts. For instance, two different functions can use the same names for local variables without causing conflicts. That of course, means fewer errors and debugging problems. With just a few exceptions, then, all of the code in your applications should be in functions so all of the variables are local.
  • If you misspell the name of a variable that you’ve already declared, it will be treated as a new global variable. With this in mind, be sure to include the keyword when you declare new variables and always declare a variable before you refer to it in your code.

Note: Use local variables whenever possible. Always use the var keyword to declare a new variable before the variable is referred to by other statements.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!