Namespaces in JavaScript

Namespaces are a common technique used in many programming languages to avoid naming collisions between different parts of your code. Unfortunately JavaScript doesn’t have built in namespace support, but it can be implemented fairly simply by creating a nested hierarchy of objects in the global namespace. A bit like this:

var My = My || {};
My.Cool = My.Cool || {};
My.Cool.Namespace = My.Cool.Namespace || {};

My.Cool.Namespace.showMessage = function(msg) {
    $('#messageBox').html(msg).show();
};

The problem with this is that it’s pretty verbose. It would be far better if you could have a function to declare a namespace and simplify things.

There are several different approaches to this knocking around. Usually, they look something like this:

var ns = namespace("My.Cool.Namespace");
ns.showMessage = function(msg) {
    $('#messageBox').html(msg).show();
};

My approach is a little bit different. Your namespace function takes a second argument, a function which is called to initialise your namespace. You can do this by assigning properties to the this object in the function body:

namespace("My.Namespace", function() {
    "use strict";

    this.showMessage = function(msg) {
        $('#message').html(msg).show();
    };
});

My.Namespace.showMessage('Hello world');

The advantage of this approach is that it implements the JavaScript module pattern, enclosing the entire contents of your file in a single function. Another thing I’ve implemented is the ability to create shortcuts to other namespaces. You can do this by passing them in an additional array to the namespace() function, which then forwards them on to the initialiser:

namespace("My.Namespace", [jQuery, Backbone], function($, bb) {
    "use strict";

    // bb is a shortcut for the Backbone namespace of
    // backbone.js; this example creates a Backbone model
    // called My.Namespace.Note

    this.Note = bb.Model.extend({
        initialize: function() { ... },

        author: function() { ... },

        coordinates: function() { ... },

        allowedToEdit: function(account) {
            return true;
        }
    });
});

I’ve put my namespace function on GitHub, along with some more detailed instructions on how to use it.

How good is your JavaScript?

We web developers vary widely in our JavaScript skills. We shouldn’t — it should be one of our core competences — but even so, at one end, you get people who avoid it altogether, or at best just fudge along and more or less busk it. Meanwhile, at the other end, there is a growing community of developers who exhibit a high degree of proficiency in the language, and use it effectively on large, well structured codebases.

Unfortunately, it can be difficult to know exactly where you yourself stand in the great scheme of things, and it’s all too easy to think you’re better than you are, so I thought I’d jot down some different levels of JavaScript experience and skill to measure yourself against. These are they.


0. You avoid it altogether and insist on using Silverlight instead.

1. Your use of JavaScript is limited to searching the web for jQuery plugins, and snippets that you can copy and paste.

2. You are able to write your own short scripts (<100 lines or so) but these are fairly simple and mainly flat and strictly procedural in organisation. You know the basics of JavaScript syntax but would be hard pressed to say exactly which data types are available to you, and if you are aware of the var keyword, you don’t know what it does. You are scared of cross-browser language differences, though you aren’t able to give any specific examples. Your JavaScript reference of choice is W3schools. You have never heard of CoffeeScript.

If you don’t see anything wrong with setTimeout("myEvent();", 1000), you fall into this category.

3. You understand JavaScript’s scoping rules, the var keyword and the (function() { ... })() construct. You understand how to use functions as first class objects, and you know exactly what jQuery returns from a call to $('.selector'). You think CoffeeScript is a solution looking for a problem. You know who John Resig is.

4. You are familiar with JavaScript’s object model and know how to implement private and public members and class inheritance and to apply the SOLID principles to JavaScript code. You are not afraid of more ambitious JavaScript projects, though you still think the language can get pretty unwieldy. You have written your own jQuery plugins. You understand the point of CoffeeScript, even though you may never have used it. Your JavaScript reference of choice is the Mozilla Developer Network. You know who Douglas Crockford is.

5. You know that Automatic Semicolon Insertion is not a browser-specific bug, but a feature clearly defined in the ECMA standard. You are confident with larger JavaScript projects, and use frameworks and libraries such as backbone.js, knockout.js and require.js to structure your code. You use JavaScript unit testing frameworks such as Jasmine, QUnit or Mocha, and tools such as JSLint and ECMAScript 5′s "use strict" directive to validate your code structure. You consider W3schools unreliable and are able to say exactly why. You understand how to optimise your code for performance. You know who Brendan Eich is.

6. You build applications which use JavaScript extensively if not exclusively, and have a working knowledge of both Node.js and CoffeeScript. You are able to spot and avoid memory leaks in JavaScript applications. You have contributed code to jQuery or another popular JavaScript library. You are aware of the CommonJS project. Your JavaScript reference of choice is the ECMA standard itself. You know who Jeremy Ashkenas is.

7. You are Douglas Crockford.


I think on this scale I’d probably rate myself at around 4 or so, aspiring towards 5 or 6 though not quite there yet. What about you? Where do you see yourself on this scale?