One of the last installments from my series on javascript interview questions.
Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?
Form most languages, global variables are considered a “bad thing”. JS is no different, but it probably has more severe consequences than most languages.
Some points on why global variables are generally bad (taken from Cunningham & Cunningham with modifications for easier reading):
- It’s harder to read the code and reason about it when variables seem to appear out of thin air (but really from the global scope).
- Anyone can update a global variable from any point in the program at any time (and from any thread if there’s more than one going).
- General code smell - if you're too lazy to put the variable only where it needs to be then what other corners are you cutting?
- It’s probable that you'll encounter global variable name clashes. Since there’s only one namespace you're more likely to double up on a variable name.
Global variables are particularly bad for JS.
Not only are all of those points above true (and a few others I didn’t include), but for JS specifically global variables can be particularly problematic. This is because JS defaults all variables to the global scope unless they are explicitly defined elsewhere. Here’s an example:
1
2
3
4
5
6
function badlyScoped() {
globalVariable = "I'm a global variable";
}
badlyScoped();
console.log(globalVariable); // logs "I'm a global variable"
Well isn’t that terrifying! We thought we were creating a local variable, since it was defined within a function, but nope! We forgot the var
keyword, which would make the variable local. Here’s a corrected version:
1
2
3
4
5
6
function wellScoped() {
var localVariable = "I'm a local variable";
}
wellScoped();
console.log(localVariable); // throws: "localVariable is not defined"
This is a quirk (some say a mistake) of JS. It makes global variables particularly dangerous since you might not even know you were creating one. So watch your back and don’t forget to use var
!
Resources:
- a more in depth discussion about why globals are bad
- some ways to avoid global variables
- stackoverflow question about why globals are bad