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 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
< p id = "neveropen" ></ 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("neveropen").innerHTML = "Marks = "+Marks; } // Changing value of global // Variable from outside of function document.getElementById("Geeks").innerHTML = "Marks = "+Marks*20; </ script > |
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
< p id = "neveropen" ></ p > < script > function a(){ // Declaring global variable using window object window.marks=10; } function b(){ // Accessing global variable from other function document.getElementById("neveropen").innerHTML ="Marks = "+window.marks } a(); b(); </ script > |
Output: