Kennis Keep your global namespace clean

Keep your global namespace clean

A good piece of advice from our JavaScript tech day today: keep your global namespace clean. There is two options to make that happen: 1) good intentions, 2) unit test it.

I have a lot of good intentions, but unit tests seem to work better. Here is the Jasmine code:

describe("General tests", function() {
describe("globals", function() {
it("should expose only a certain amount of variables", function() {
var expectedGlobals = ["util", "KeyCode", "logger", "l", "langur"];
var exposedGlobals = detectGlobals.analyze();
var expectedButNotDetected = _.difference(expectedGlobals, exposedGlobals);
var detectedButNotExpected = _.difference(exposedGlobals, expectedGlobals);

Note that you have to run this test at the very end of your testsuite to detect any globals that are created during the execution of the tests.

Go here for the gist with the Javascript that does the actual work (that gist was heavily inspired by this code, credits go to kangax (Juriy Zaytsev) ).