Global variables in Javascript
Global variables are evil. Although possibly nifty for very small programs it quickly clutters the global namespace and increase the risk for name collisions as are program grows larger. The risk for collisions are even greater when using different libraries and widgets.
There are three ways to define a global variable in Javascript.
The first way is to declare the variable outside of any function.
var myGlobalVar = value;
The second way is to assign it as a property to the global object, which in web browsers are the window object.
window.myGlobalVar = value;
The third way is to use it without defining it. In this case it doesn’t matter if it’s inside of a function or not. This is called implied global.
myGlobalVar = 'Hello world';
A great way to minimize the use of global variables is to store them all in one global object. By doing this you can keep all you variables and functions in one place, greatly reducing the risk for name collisions.
// Define your global object
var myObj = {};
// Add property (variable) to it
myObj.myVar = 'Hello world';
// Add method to it
myObj.myFunctions = function() {
// Do cool stuff
};
The Javascript language was designed with global variables like this to make it easy for beginners to start coding. The side effect being that it’s easy to forget to define a variable and thereby creating bug that are hard to discover. So do yourself a favor and avoid global variables whenever possible.
Pingback: Anonymous
Pingback: Learning Javascript « Sarfraz Ahmed's Blog