Introduction
In JavaScript, global variables refer to those variables that are defined outside of any function, allowing them to be accessed from any location within the script, including within those functions.
In JavaScript, global variables play a crucial role in programming by providing access across various parts of a script. These variables are declared outside of any functions and reside in the primary segment of the source code.
Syntax:
In JavaScript, the declaration of global variables adheres to the following syntax:
//outside of any block or function
let globalVal = 3;
How to declare a Global Variable in JavaScript?
In JavaScript, global variables can be established by declaring them outside of any function or block scope. Such variables are designed to be accessible throughout the entire script, allowing for their use in any part of the code.
Let’s explore the process of declaring a global variable in JavaScript:
//outside of any block or function
let globalVar1 = 3;
var globalVar2 = 5;
const globalVar3 = 1;
Examples of JavaScript Global Variable
Example 1
//Global scope
let myVal = 20;
function addOne() {
myVal = myVal + 1;
}
function print(val) {
console.log("value is :"+ myVal);
}
addOne();
print(); //output => value is 21
Output:
Example 2
Output:
We have defined a global variable named themeVal that specifies the display color, and it has been assigned the value "dark." There are two conditional blocks that evaluate the value of this variable, triggering either the darkTheme or lightTheme function based on the result of this evaluation. Consequently, the darkTheme function will be executed, which will log "current value of theme is dark" to the console.
Example 3
var appName = "MyApp";
// Another script overwrites it
var appName = "OtherApp";
console.log(appName);
Output:
Automatic Global Variables
When variables are declared in your code without the use of the keywords var, let, or const, they automatically become global variables. This means that their scope is not limited and they can be accessed from any location within your program.
Example
In the following code, we are defining the variable 'a' without utilizing any specific declaration keyword within the function. Despite 'a' being defined inside the function, it is considered a global variable since we did not use a keyword to declare it.
The result demonstrates that the variable 'a' can be accessed both within the function and externally.
Example
<html>
<head>
<title> JavaScript - Global variables </title>
</head>
<body>
<p id = "demo"> </p>
<script>
const output = document.getElementById("demo");
function test() {
a = 90;
output.innerHTML += "a -> Inside the function = " + a + "<br>";
}
test();
output.innerHTML += "a -> Outside the function = " + a + "<br>";
</script>
</body>
</html>
Output:
Benefits of a Global variable
There are some benefits of using global variables in JavaScript. Such as:
- Accessibility: In JavaScript, global variables provide a convenient way to share data across different parts of the program without passing them as function arguments.
- Ease of Use: They simplify the sharing of data between functions and modulus, which reduces the need for complex parameter passing mechanisms.
- Data Sharing: Global variables facilitate easy sharing of data between different functions or modules, eliminating the need to pass data as arguments or return values.
- Constant Values: In JavaScript, global variables are well suited for storing constant values such as pi or e, as they need to be declared only once and remain in scope until the program ends.
- Maintenance: When specific changes are required throughout the entire program, it becomes more accessible to apply via global variables.
Limitations of Global Variables
While global variables may seem convenient, they also have some limitations, such as:
- Namespace Pollution: Global variables can lead to namespace pollution, where variable names clash or conflict with each other. It can result in unexpected behaviour, bugs, or errors in your code.
- Security Risks: In JavaScript, global variables are accessible from anywhere in the code, which makes them vulnerable to security risks such as data leaks, injection attacks, or unintended modifications.
- Code Maintainability: Code that relies on global variables can be harder to maintain and debug. It becomes challenging to track the flow of data and dependencies, which leads to code that is less modular, reusable, and scalable.
- Performance Issues: In JavaScript, accessing global variables can impact the performance of your application, especially in large codebases.
Conclusion
In conclusion, the topic discussed herein, we considered the use of global variables in various contexts, focusing on variable naming conventions. We also considered the redeclaration of the variables' values, the scope restrictions and hoisting associated with the first var variable, and the let and const variables used in JavaScript.