What’s a Namespace?

You may have heard the term “namespace” and had a vague idea (or no idea whatsoever) what it referred to. A namespace is a coding term that pops up from time to time as something you should probably know about but don’t have to get through your day. Knowing when to use a namespace is both a good coding practice and a courtesy to other developers. In this article I’ll give you an overview about what a namespace is and how it works with a focus on JavaScript.

A namespace is essentially a wrapper for your code’s variables, functions, constants, and classes. This wrapper prevents “collisions” (a.k.a. clashes, conflicts, etc.) with other people’s code. For example, if you grab a script from a site and drop it into your web page you might find that for some reason that the script doesn’t work. Or you may discover that code you wrote, which worked before you dropped in this new code, has stopped working. After doing some debugging you determine the problem stems from both you and the person who wrote the script you grabbed are using the same variable names purely by accident. Your code works fine on its own, as does this script you grabbed; however because you both inadvertently used the same name for a variable, one of your variables is being overwritten by the other. For example, you both may have used a variable named firstName. Now while this might not be hard to fix, it can be time consuming and frustrating to track these kinds of errors down. Plus, simply renaming the conflicting variables can lead to other errors springing up. With more and more developers writing code to be shared, the odds only increase that someone will step on someone else’s code. This is where namespaces come in.

Namespaces basically wrap all your variables in a tidy package so that you can use whatever names you like without them colliding with someone else’s variables. A key step is to give your namespace a unique name because if your namespace has the same name as someone else’s namespace, well pretty much the universe will implode on itself. But fear not, it’s far easier to change a namespace’s name in the event of duplication than it is to replace all the instances of one or more variables in your code.

Again, while namespaces are not required, they can be an extremely valuable tool.

JavaScript Namespaces

By default, variables in JavaScript are global in scope unless they’re defined within a function using the var declaration. This means that you can access a variable anywhere in a script since they are within the global namespace. Variables defined within functions using the var declaration (e.g. var foo = 2;) are only accessible from within that function. By creating your own namespace you segregate your variables from the global namespace and prevent other code from accidentally accessing them, similar to the way using the var declaration in a function segregates that variable from being accesses from outside of that function. If you and I both write code that use a variable named firstName and then include both scripts on the same page, one of the scripts will overwrite the other’s use of firstName. As the book JavaScript the Definitive Guide states, “If you want to write a module of JavaScript code that can be used by any script and can be used with any other module, the most important rule you must follow is to avoid defining global variables. Anytime you define a global variable, you run the risk of having that variable overwritten by another module or by the programmer who is using your module. The solution instead is to define all the methods and properties for your module inside a namespace that you create specifically for the module.”

One of the easiest and most widely-used methods for defining your own namespace in JavaScript is to use an object. For example,

var superspace = {};

creates an empty JavaScript object which can then be used as our namespace. In the past we might assign a value to our firstName variable like

var firstName = "John";

however by using an object we can now do the same thing via

superspace.firstName = "John";

You can also place functions in your namespace object in a similar way. For example,

superspace.getFirstName = function() {
return superspace.firstName
};

The only real difference when using namespaces is that you prefix the name of the namespace object (superspace) to the variable name. This little change is what allows us to encapsulate our variables and keep them protected. It’s also possible to create your namespace object and your variables and functions at the same time. For example, using the same code as before you could write:

var superspace = {
    firstName : "John",
    getFirstName : function() {return superspace.firstName}
};
document.write(superspace.getFirstName()); // outputs "John"

Now, superspace.firstName and superspace.getFirstName are available globally within our page, however collisions won’t occur unless someone else is also using an object with both the same name (superspace) and the same variables (firstName and getFirstName).

Another way to create a namespace is through self-executing or self-invoking functions. Self-executing and self-invoking functions are simply anonymous functions (no explicit name) that are executed immediately after they are read by the browser. For example:

var superspace = (function() {
var firstName = "John";
var getFirstName = function(){return firstName};
    return {getFirstName:getFirstName};
})();
document.write(superspace.getFirstName()); // outputs "John"

A self-invoking function is a normal function, just with a set of parentheses appended to the end. The set of parentheses at the end tell the browser to execute the function just as if you were invoking a normal, named function (e.g. getFirstName();). Since self-invoking functions aren’t reusable, they’re really not functions in the truest sense since functions are meant to be reused. To differentiate self-invoking functions from normal functions, it’s recommended that self-invoking functions are wrapped in parentheses. To be honest, I prefer the simple object method of namespacing over the self-invoking function method because it’s easier to read and needs less code to accomplish the same task.

One thought on “What’s a Namespace?”

Leave a Reply

Your email address will not be published. Required fields are marked *