Non-Polluting JavaScript

All scripts on a web-page excecute in a single context, one after another in the order in which they appear in the page’s HTML (or in which thy are included from external files). This means that the variables and functions defined in a script are accessible by the scripts that run after it. If you’re writing scripts that are intended to be self contained, so that they can be dropped into any page without interfering with the other scripts on that page, you may want to consider making your script what I call a ‘non-polluting’ script. That is, a script that doesn’t alter or define any global variables or define any functions. A script that leaves no traces behind it, beyond its intended effect.

Such a script is made possible by the concept of anonymous functions. When you call a function in JavaScript you generally do it by typing its name followed by the list of parameters enclosed in parentheses, eg.:

myFunc(arg1, arg2);

In fact, you can call an anonymous function by replacing that function name in the code with the function definition, eg.:

    // function code goes here

This has the effect of defining an anonymous function (notice that it’s never given a name) and then excecuting it. If you enclose your entire script withing such an anonymous function it will excecute as normal but none of the variables you define will be defined outside of the anonymous function.

There is one important change you may have to make to your script to be able to put it inside an anonymous function like this. That is that you must ensure that all of your variables are defined explicitly using the var keyword. Otherwise they will be created in the global scope instead of the function scope.

And that’s it. That’s all you have to do to make sure that your script is entirely self-contained and non-polluting.