X



Home>Tutorial>

What is JavaScript Global Variable Advantages and Disadvantages

Nuelson Penuel Saturday, August 21, 2021 Javascript

Introduction

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.

What is JavaScript Global Variable

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.

What are the Advantages of JavaScript Global Variable

  1. JavaScript global variables makes it easier for you to access the variables anywhere in the JavaScript file without having to repeat variable declarations.
  2. It can be used to reduce the size of JavaScript file since variables are declared once

What are the Disadvantages of JavaScript Global Variables

  1. Too many global variables will occupy more memory units since global variable is stored in static storage which requires memory allocation.
  2. Global variable may increased the risk of using wrong values if tempered somewhere else
  3. Global variable increment is slower than local variables
  4. Global variables reduce the readability of the function code.

Example of JavaScript Global Variables

<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

Declaring JavaScript Global Variable Inside Function

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);  
}  

Conclusion

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.

| | Views(829)

See Demo | Download File


Add your comment. Indicate code using code tag


Words: 0 | Chars: 0 | Reading Duration: 0



Images Attachment




Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services