JavaScript elegant namespace declaration

Emulating multilevel namespaces behavior in JavaScript shouldn’t be so complicated. We all know that namespacing in JavaScript is done by nesting objects. But for each nested object we have to check if it already exist so we wont overwrite it with the new object. This can happen if you write a lot of code and dynamic functional languages become harder to tame as the number of lines grows and especially JavaScript can be hard to organize and keep modular. In Python, for instance, namespace and import functionalities already exist, but not in JavaScript so we have to use tricks to emulate these behaviors.

var namespace = function(str, root) {
var chunks = str.split('.');
root = window;
var current = root;
for(var i = 0; i < chunks.length; i++) {
if (!current.hasOwnProperty(chunks[i]))
current[chunks[i]] = {};
current = current[chunks[i]];
return current;
// —– USAGE ——
namespace('ivar.util.array'); = 'bar';
namespace('string', ivar.util); = 'baz';

view raw


hosted with ❤ by GitHub


The trick for multilevel namespaces in JavaScript is merely an automation of the checking if the object exists so not to overwrite it, and if it doesn’t exist it nests another object by the given name from the input string. The input string is formed by names of the objects joined by a dot, for instance “ivar.util.lang”. Breaking the string by a dot we start from the root object, that is the window if no other root object is provided and we ask for existence of every of these three properties., and create them if they don’t exist.

After developing this simple method I found that YUI has almost exact system for creating namespaces in JavaScript. Be sure to check it out.


One comment

  1. […] / including modules in JavaScript. Combining this require module with namespace method described here provides the ultimate system for JavaScript modular […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: