JS: don’t touch the global scope

Published on: December 30, 2014

Tags: js and interview-questions

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):

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:


comments powered by Disqus