Why are closures better than global variables for preserving variables?

It's a scoping issue. Global variables are just that: Global, to everyone. With closures, the scope (visibility) of the variables can be better controlled, which means the possible unintended side effects can be better controlled.

http://en.wikipedia.org/wiki/Global_variable

[Globals] are usually considered bad practice precisely because of their non-locality: a global variable can potentially be modified from anywhere (unless they reside in protected memory), and any part of the program may depend on it. A global variable therefore has an unlimited potential for creating mutual dependencies, and adding mutual dependencies increases complexity. See action at a distance


Two words : race conditions.

If you set a variable in the global scope while its intended usage is local to a function instance you run the risk of having two (or more) unique instances accessing and manipulating this global variable and having all instances behave unpredictably.

There are plenty of other reasons why you should be extremely careful about storing local state in the global space.

One would be re-using the state of the last instance that set this variable (if you don't have multiple instances active simultaneously).

There are also possible conflicts with other pieces of code that rely on a global variable with the same name.

Aesthetically you also turn the global namespace into a mess (lots of random variables there without any direct information as to why they are there in the first place).

Putting variables into the global space is error-prone and makes a mess of the runtime view. The scoping possibilities of JS also make it unnecessary, which is why nobody does it (except for things that really belong there).

As an additional comment, don't mention your age or brag about your coding prowess in future questions. It's not relevant to the question.


Well there is only one global namespace in JavaScript, so it would be pretty hard to use different Frameworks/Toolkits on the same page, because sooner or later, variable names would begin to clash.

Also closures provide a way to emulate private variables:

function Counter(start) {
   var count = start;
   return {
       increment: function() {
           count++;
       },

       get: function() {
           return count; // only gives you the value, but no write access
       }
   }
}

But that's a rather "dumb" example, closures are especially helpful when it comes to callbacks of all sorts, you don't want to manage global arrays which hold the data for each callback, it a lot simple, and cleaner with closures.

For an extreme use of closures take a look at a Class implementation for JavaScript. (Disclaimer, code was written by me.)

Here proto keeps track of the raw properties of each class, but it's still available to extend which then can add those properties to other classes when they inherit from another.