Skip to content
Related Articles

Related Articles

How to declare Global Variables in JavaScript ?

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 21 May, 2021
Improve Article
Save Article

Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable. 

Global Variables are the variables that can be accessed from anywhere in the program. These are the variables that are declared in the main body of the source code and outside all the functions. These variables are available to every function to access. 

  • Global variables are declared at the start of the block(top of the program)
  • Var keyword is used to declare variables globally.
  • Global variables can be accessed from any part of the program.

Note: If you assign a value to a variable and forgot to declare that variable, it will automatically be considered as a global variable.

Example 1: In this example, we declare the variable at the start of the program outside every function using the var keyword. 

HTML




<!DOCTYPE html> 
<html
  
<body>
    <center>
        <p id="geeks"></p>
  
        <p id="Geeks"></p>
  
          
        <script>
            var Marks = 10; 
  
            // Declaring global variable outside the function
            myFunction();
                // Global variable accessed from 
                // Within a function
  
            function myFunction() {
                document.getElementById("geeks").innerHTML =
                    "Marks = "+Marks;
            }
            // Changing value of global
            // Variable from outside of function
  
            document.getElementById("Geeks").innerHTML =
               "Marks = "+Marks*20;
        </script>
    </center>
</body>
  
</html>

Output:

Example 2: Declare the Global variable within a function using a window object. Variable declared using window objects are global variables and can be accessed from any portion of the program.

HTML




<html>
<body>
  <p id="geeks"></p>
  
    
  <script>
    function a(){  
      // Declaring global variable using window object  
      window.marks=10;
    }  
    function b(){  
      // Accessing global variable from other function 
      document.getElementById("geeks").innerHTML ="Marks = "+window.marks 
    }  
    a();
    b();
  </script>
</body>
    
</html>

Output:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!