JavaScript - Global Variables
JavaScript - Global Variables
JavaScript Global Variables
Theglobal variablesin JavaScript are the variables that are defined outside of the function or any particular block. They are accessible from anywhere in JavaScript code. All scripts and functions can access the global variables.
You can define the global variables using thevar,let, orconstkeyword. The variables defined without using any of the var, let or const keywords automatically becomes global variables.
JavaScript Global Scope
The global variables have global scope. So a variable declared outside of a function or block has global scope. Theglobal scopeis visible or accessible in all other scope. In client side JavaScript the global scope is the web page in which all the code is being executed. A global variable declared withvarkeyword belongs towindowobject.
var x = 10; // Global Scope
let y = 20; // Global Scope
const z = 30; // Global ScopeHere the variables, x, y and z are declared outside of any function and block, so they have global scope and are called global variable.
Global Variable Examples
Letβs learn more about global variables using the example below.
Example
We have defined the x, y, and z global variables in the code below. You can observe that variables can be accessed anywhere inside the code.
Output
x = 10
y = 20
z = 30Example
In the example below, we have defined the variables a and b using the var and let keywords. You can see that a and b variables can be accessible inside the function or outside the function as they are global variables.
Output
a -> Inside the function = 10
b -> Inside the function = 20
a -> Outside the function = 10
b -> Outside the function = 20Automatic Global Variables
When you define the variables anywhere inside the code without using thevar,let, orconstkeywords, the variable automatically becomes theglobal variableand can be accessible anywhere inside the code.
Example
In the below code, we have defined the variable βaβ without using any keyword inside the function. Even if we have defined the variable in the function, it becomes global as we havenβt used any keyword to define the function.
The output shows that variable βaβ can be accessible inside or outside the function.
Output
a -> Inside the function = 90
a -> Outside the function = 90Defining the global variables inside the function or particular block is not a good practice, as naming conflict can occur in the code.