Skip to content
Related Articles

Related Articles

Improve Article

How to declare Global Variables in JavaScript ?

  • Last Updated : 21 May, 2021
Geek Week

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :