Global variables are an essential part of JavaScript, and they are used extensively in JavaScript code. As a JavaScript developer, it’s essential for you to develop a firm understanding of a JavaScript global variable and learn its usage.
What is a JavaScript Global Variable?
In general, a JavaScript global variable is a variable that you declare outside a function. From a browser’s viewpoint, a global variable is the one that you declare using window object.
The key highlight of a global variable is that it has a global scope. It means that you can use a global variable throughout the program. In other words, when you declare a global variable in a JavaScript program, you have the flexibility to use it in any block of code or a function.
Below is an example of declaring a global variable:
<script> var a = 5; //global variable function comparison () { var b = 10; if(a<b) { console.log ("a is less than b"); } else { console.log ("b is less than 5"); } } comparison();
</script>
In the above example, you can see that we have declared a global variable a that is not within any function. However, we have used the same variable a inside the function comparison() without declaring it. It simply shows that the variable a has a global scope and we can use it anywhere within the JavaScript code.
Overriding the Value of a Global Variable
While global variables have global scope, it is possible to override their values within a function by declaring it explicitly with a new value.
Following is an example where we override the value of a global variable:
<script>
var a = 5; //global variable function comparison () { var a = 10; var b = 10; if(a<b) { console.log ("a is less than b"); } else if (a=b) { console.log("a is equal to 5"); } else { console.log ("b is less than 5"); } } comparison();
</script>
In the above example, you can see that we declared global variable a with a value of 5. However, we declared variable a with a new value of 10. When we execute this code, the variable a will take value 10, and the output of the program will be:
a is equal to 5
However, you need to note that the value of variable a will remain 5 outside the function comparison().
Takeaway
A JavaScript global variable is a variable with a global scope. Once declared, you can use a global variable throughout the program. Also, it is possible to override the value of a global variable by declaring it within a function and assigning it with a new value.
People Who Read This Article Also Read:
Hi! I am Pankaj, a full-time content specialist and a part-time programmer and marketer. I love to explore new places and also new ideas. I am an inquisitive person with a passion to learn new skills through every possible opportunity that comes in the way.