JavaScript: Global Variables
One of the biggest issues that you can run into with writing JavaScript is abusing the shared global namespace, and overwriting the variables of an unrelated script. Everything that you declare in JavaScript is available to every other script on the page, unless you wrap the declaration in a function. Also, if you use a variable without declaring it (even within a function), it will be declared for you in the global scope.
There are a couple of remedies we have against creating a global soup of conflicting variables. Knowing is half the battle, so step one is just keeping an eye out. Recognize when you’re creating a function or variable, and make sure that it’s not a global. The main technique for this is to declare everything inside a function. If you’re writing jQuery scripts, most of your script is probably being written inside the callback passed to jQuery(document).ready()
, so you’re mostly safe already. If you’re not using a function already, you can wrap your code in an immediately invoked function expression.
Step two is to catch when you miss declaring a variable. There are two ways to do this. The first is to turn on strict mode, so that browsers which support strict mode will throw an error when you try to access an undefined variable (instead of defining it as a global). In addition, you should be running your code through a linter (JSLint or JSHint) to catch issues like this.
So, now that you know how not to expose global variable, what about if you need to? If you need to write code in one script and reference it from another, you’ll need to expose a reference to that code somehow, right?
In this case, you should still probably be using all of the above techniques to keep the scope clean, but then explicitly expose anything that you need to. Again, if you’re using jQuery, this is fairly natural. Your script will take a reference to the global jQuery function, and you can add your script as a plugin to jQuery.fn
. If you’re not exposing a jQuery plugin, you can take a reference to the global window
object, and add your object explicitly. As an example:
(function (window, $) { “use strict”; // turn on strict mode var x = 10; // x will not be accessible outside of this function y = x * 20; // y will be declared as a global variable, unless the browser supports strict mode $.fn.myPlugin = function (args) { ... }; // expose your plugin to the rest of the page window.textbox2_validate = function (sender, args) { ... }; // expose a standard function }(this, jQuery)) // immediately invoke this function expression, passing in this (a reference to the global scope) and jQuery