Declaring global variables in JavaScript

By Santhosh N

This explains different ways of declaring global variables and necessary precautions need to be taken while doing so.

To begin with, in JavaScript to declare a variable we use var


Ex: var myVar;


If the variable declared inside a function or control structure its scope is limited to that particular function/control block only.


To declare global variables in JavaScript, just declare them outside functions.
But, is there a way to declare global variable inside the function? The answer is yes, we can.
One could declare global variable by removing var keyword and use that directly


Ex: myVar = ‘str’;


If you assign a value in this manner, myVar becomes a global variable.


Note: Please be careful while doing this as if you have any other variables with the same name in global scope (within the same js file or even external files which might be having global variables), it could cause adverse results.

Related FAQs

This is how trimming of a string can be done in javascript is simpler manner.
This is a way to check if the given string is in numeric format or not
Get the random number within the specified range
This explains how to show a counter using jQuery to show down the countdown or can be used to show progress as well
This explains how to focus the first textbox control inside the Div using jQuery
This explains how to get the browser name and version using Javascript which is useful to display page elements accordingly to give cross browser compatibility.
Declaring global variables in JavaScript  (1434 Views)