
One of the pitfalls a lot of JavaScript developers get caught by, especially when starting out, are implied globals. So what is an implied global?
implied = "global";
Any time you use a variable without having declared it using the var keyword, you are creating an implied global. When JavaScript is executed inside a browser the global object, for convenience, usually refers to the window DOM object. Any implied globals becomes a property of this global object so, the following is all valid:
implied = "global"; console.log(implied); // global console.log(window.implied); // global console.log(window['implied']); // global console.log(this.implied); // global
This in itself might not seem like much of a problem however but, what would happen if a third party script created a global variable called tracker and later in our own code we also create a variable named tracker but, without declaring it using var?
// Third party code
tracker = true;
function track() {
if(tracker) {
console.log("Tracker: " + tracker);
} else {
console.log("This should not happen");
}
};
// Our code
function antiTrack() {
tracker = false;
console.log(tracker);
};
In the above scenario, if antiTrack() is called before track(), the value of tracker will now be false which will throw track() into the else branch it should never enter.
This can clearly lead to problems and unexpected results. It is therefore best to avoid these situations by always declaring your variables using var. If we then change the above to the following:
// Third party code
tracker = true;
function track() {
if(tracker) {
console.log("Tracker: " + tracker);
} else {
console.log("This should not happen");
}
};
// Our code
function antiTrack() {
var tracker = false;
console.log(tracker);
};
You can now safely call the two function in any order and it will always reference the correct value for the tracker variable. There is a design pattern called, the single var pattern, you can employ that will ensure you avoid these situations. I will be discussing this pattern in a follow on post.
UPDATE: Another thing to note is that, when you do not declare your variables they simply become a property of the global object and can be deleted easily, as follows:
// Third party code
tracker = true;
function track() {
if(tracker) {
console.log("Tracker: " + tracker);
} else {
delete tracker;
}
};
If your code relies on this variable existing, which it most likely does, things will fall apart and it will be incredibly difficult to debug. If however, your tracker variable was declared using var, it would not be deleted using the code above.
Image Courtesy: Feuillu
