Javascript : Introduction to Namespaces

In this article, we will talk about namespaces in Javascript and why and how to use them.

Globalization can be a pain in a**

Let’s say that you are writing an boatload of client-side javascript for a project. Now, it is more likely than not that you are using at least 1 third party library (jQuery and Modernizr being the usual suspects). For big projects, you might also have a whole team of developers working on different files. So, now what happens?

For the sake of hypothesizing, let’s create 2 files, call them product.js and client.js.

Client.js

var retrieve = function() {
	//return client data;
};

Product.js

var retrieve = function() {
	//return product data;
};

Oh boy! If both these scripts are included in the same file, and retrieve() is called, what happens? Well, the answer is that one of the scripts will overwrite the other’s logic. It’s very easy to extrapolate the chaos things like these can cause in large projects.

You see, in Javascript, both of these will be hoisted up to the global scope, and the more variables we create in the global scope, specially being unaware of what is in the other files that may be included, the chances of collision and overwriting increase. Which is why globalization is bad.

Introduction to Namespaces

With PHP 5.3, namespaces were introduced. So, you could write code like this.

/**
 *  Location of the file : root-folderobjectsClient.php
 */
namespace objects;
class Client {
	public function retrieve() {
		//retrieve data from client
	}
}

The objects namespace is just an added classifier to resolve the scope of the Client class. Now, there can be yet another class named Client, but in another namespace, and you will be able to use both classes at the same time, because you can tell the PHP compiler to resolve the class by its namespace. Unfortunately, JavaScript does not offer a native way to do this, which brings me to the next section of this article.

A coder’s gotta do what a coder’s gotta do

Since programming is very heavily dependent on code hacks, with people always looking for a better way to do things, a sort of a relief tent was set up for Javascript, which provided namespaces to the language. The syntax for that is actually fairly simple.

var MyApp = MyApp || {};

That’s just it. But wait, the trick lies in how we can use it to resolve multiple issues. First, we segregate the logic for the product and the client. Second, we’ll augment everything into one single cohesive entity, instead of creating small packets of code for different parts of the app.

To clarify how, let’s first see how our namespace will work. This is the motherlode of all the sub-namespaces we will be using. So, developers working on the Product module will create the Products namespace, and so on and so forth. They will also keep this line at the top, so as to hoist all their logic into a single entity, or a single scope. As an example, javascript files might look like this.

Product.js

var MyApp = MyApp || {};

MyApp.product = {
	retrieve : function() {
		//retrieve product data
	}
};

Client.js

var MyApp = MyApp || {};

MyApp.client = {
	retrieve : function() {
		//retrieve client data
	}
};

Basically, what the first line does in both the files, is to direct them to use the MyApp namespace. If it exists, use it as is, else create it. From then on, everything is defined under the scope of MyApp, which makes it super simple to classify and use.

Of course, there’s no fun without giving an example. This is how you can use those namespaces without causing a collision or overwriting of variables or logic.

var clientData = MyApp.client.retrieve();
var productData = MyApp.product.retrieve();

Conclusion

As you can see, with the advent of so many third party essential libraries, we need to keep our own logic from breaking any of them, which is why namespaces are very very useful. You can create namespaces within namespaces, which is exactly what we have done with the client and product sub-namespaces under the MyApp namespace. As long as there is no naming collision in the project with sub-namespaces, multiple files of logic can be created, and used according to the need of a particular HTML file.

Instead of creating one gigantic mega file worth hundreds of KBs, one could create hundreds of such files, and load them on demand by using AMD. This speeds up the page load and makes for a happy browser. However, using pure namespaces has its own caveats, so we need to use modules, but that’s for yet another day. Till then, yippee-ki-yay, developer!.