Javascript, keeping it clear

by Richard — 3 minutes

Note that this blog is in no way written as a "best practice" or "do it this way" kind of blog. I am not, nor do I aspire to be, the worlds greatest javascript programmer. I do however like my code clear and structured. Now lately some colleagues have asked me how I write my code and that in turn prompted this blog. In short the best way to keep your Javascript clear is using namespaces.

The use of namespacing is very simple and should cause you no problems. As you will come to see it will be both easy and clear for fellow developers to read and modify your code. So yes, if you wish to remain the javascript magician with obscure code that no other developer wants to touch feel free to not use them. Creating a namespace:

var namespace = {};

That's it. No more and no less. Offcourse this isn't functional but then again it needn't be just yet. To make it functional we add methods to the namespace. We can do this in one of two ways. The first is adding it to the namespace declaration like so:

var namespace = {
  doSomething: function () {},

The second is by adding it as an attribute like so:

namespace.doSomething = function () {};

Both versions create the following method call: namespace.doSomething(); I personaly prefer and advise the first of the two options. This is because all code is grouped together. And that was what we set out to do in the first place. So don't just group your method calls but the code aswell. This was a short example to illustrate what we can do with namespaces. This is nice for small and simple projects. But when it gets more complex we should think about extending the namespace. Say for instance we have a namespace for a project called images and this has methods for galery and album. Then we may have specific methods for galery and album and some shared ones. In order to clear up what is what we add sub namespaces. Our namespace would then look like so:

var images = {
  shared: {},
  album: {},
  galery: {},

Note that the sub namespaces use a semicolon instead of a equals. By using this structure you can easily maintain clear and followable trails for your custom methods. But remember that keeping method body's clear is also required.