In this brief post, you will learn what is JavaScript Global variable advantages and disadvantages as well as the examples. I tried as much as possible to make this lesson as brief as I can for easy digesting.
A JavaScript global variable is any variable that is declared using window object. It can also be seen as any variable declared outside a function.
- JavaScript global variables makes it easier for you to access the variables anywhere in the JavaScript file without having to repeat variable declarations.
- It can be used to reduce the size of JavaScript file since variables are declared once
-
Too many global variables will occupy more memory units since global variable is stored in static storage which requires memory allocation.
- Global variable may increased the risk of using wrong values if tempered somewhere else
- Global variable increment is slower than local variables
- Global variables reduce the readability of the function code.
<script>
var num1=5;var num2=3;//global variable
function sum(){
var res=parseInt(num1) + parseInt(num2);
alert(res);
}
function subtract(){
var res=parseInt(num1) - parseInt(num2);
alert(res);
}
</script>
In the above example, we declared num1 and num2 as global variables
Global variable declared inside a function is done using the window object. When you use window object to declare a variable, the variable will be available to all functions that needs it.
For example;
function sum(){
window.num1 = 5;
window.num2 = 3;
var res=parseInt(num1) + parseInt(num2);
alert(res);
}
From what we have learned so far, global variables play important role when it comes to JavaScript file size reduction and also make you declare your variables once.
But, it also has its own bad side such as wrong value mistakenly given can mess up the whole objective of the script.
Therefore be careful when using JavaScript global variables.