Give a hoot

As any competent JavaScript knows, it’s not cool to litter the global namespace with variables, functions, and the like. It’s far better to encapsulate your code in an object, a series of objects, or even a closure, exposing only what you absolutely need to via the global namespace. This helps reduce the potential for collisions that will probably cause your site to break.

Occasionally, however, even closures won’t help you trap a given variable. Case in point:

var a = b = 0;
view raw pollutes.js hosted with ❤ by GitHub

If you’re familiar with languages like PHP, you might think this simple closure creates two variables with the same value, but you’d be wrong. It creates a local variable, a and a global variable b, both of which have their value set to 0.

function example()
$a = $b = 0;
view raw example.php hosted with ❤ by GitHub

In exp:easy_gists this means of sharing the value assignment of variables is perfectly legit; the difference, however, is how JavaScript and PHP treat variable scope. By default, every variable declared in PHP is scoped to the function it is called within. Global variables only come into play when you use the global declaration or the $_GLOBALS array. In JavaScript, by contrast, any variables not instantiated with a var are added to the global namespace. Hence the namespace pollution in the above example.

Revisiting the closure, it’s best to rewrite it in one of two ways to maintain the variable scope:

var a = 0, b = 0;


var a = 0, b = a;

Which solution will work best is dependent solely on context. If you’re minifying the code and the value being assigned is anything more than a single character, the latter is probably the way to go.

To help you discover and mitigate pollution in your own scripts (or to help you see what additions your standard JavaScript libraries are making to the global namespace), I’ve created a little script called EmissionsTest.js. It’s pretty easy to use, you simply include it as the first script on your page (preferably in the head of your document) and it does the rest. It will attempt to report its findings to the console (if your browser has one) or it will create a floating notice at the top of the page.

You won’t want to include this script on a production site and it’s still pretty basic, but it could be very useful for tracking down any accidental emissions in your script.

Like it? Share it

Share on LinkedIn

Share on Google Plus