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.
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.