Writing Maintainable Javascript Guidelines

April 3, 2009


We’ve been doing a lot of Javascript development lately, while writing an Ajax-based web application. Up until recently, my team’s Javascript experience consisted mainly of the occasional disable-that-checkbox function inside an .aspx web-form. Nothing wrong with that, I guess, but it doesn’t really count. If you’re going to write a lot of Javascript, you have to do so in an organized and clean way, or you’ll have a maintenance nightmare on your hands.

This is not because Javascript is a bad language. It can be quite beautiful actually. But it does allow to work in ways that are not elegant, so I would like to show you some tips on what you should do, and what you should avoid – Framework Design Guidelines style.

DO use separate .js files to store your Javascript code.

AVOID writing a lot of Javascript inside an .aspx form.

When you do the shift to a heavily scripted client, and you begin writing loads of Javascript, this approach fails miserably, for several reasons:

  1. Performance – .js files are usually cached on the client side, and .aspx are not, as they usually contain dynamic data. Also, .js files can usually be compressed, so they get even lighter to download.
  2. Maintenance – It is just easier to maintain the script code when it is in a separate file.

DO use different .js files for different modules.

It might seem obvious, but I’ve seen .js files that contain thousands of lines of un-related code. Again, this is hard to maintain. In C# we like having a separate file for each class, don’t we? Well, Javascript shouldn’t be a lot different. If you’re worried about the performance penalty of having many files, there are tools you can use to combine your scripts to a single file on deployment.

DO use a Javascript library instead of rolling your own infrastructure.

Really, these days it is just silly to write your own Ajax implementation, or your own collection types. Libraries like jQuery, ASP.NET Ajax and Dojo, already do so much for you. This will save you a lot of time and effort, and will also allow you to create cross-browser Javascript that works even on crappy-old browsers such as IE6.

CONSIDER writing only object-oriented Javascript.

Most Javascript libraries will allow you to write your code in an object-oriented manner, based on the prototype model available in the language. Object oriented code is easier to follow and understand. And yes, you even get the benefits of inheritance, design-patterns and all that good OO stuff you know from C#. Here’s how a class in the Dojo library is declared:

dojo.declare("Person", null, { constructor: function(name, age, currentResidence){ this.name=name; this.age=age; this.currentResidence=currentResidence; }, moveToNewCity: function(newState) { this.currentResidence=newState; } });

As you can see, we have a constructor, fields, methods and all.

AVOID using a lot of global variables and functions.

This is really just good programming behavior. Globals are bad! That’s what they always used to tell you, and this is still correct. Unlike C# or Java, Javascript allows you to define global variables and global functions. In fact, for many this is the standard way of scripting. I know it was for me. But when you start having hundreds and thousands lines of code, which access some variable that was defined in god-only-knows-where, you’ll see that it’s a bad idea. When you have 5, 10 or 20 .js files, you just don’t want to take the chance that two of them define the same function or variable, do you?

Granted, you can’t avoid using some globals, but you should keep this to a bare minimum. Our pattern for global functions is to use them as gateway-only to some class. Usually they will be event-handlers which just create a class and call one of its methods. We pass data around from constructor to constructor instead of defining it globally.

AVOID specifing an Html element ID in a class declaration.

This is bad:

dojo.declare("ButtonHider", null, { hide: function() { $get('MyButton').style.display = 'none'; }

This is good:

dojo.declare("ButtonHider", null, { hide: function(buttonId) { $get(buttonId).style.display = 'none'; }

Also good:

dojo.declare("ButtonHider", null, { constructor: function(buttonId) { this.buttonId = buttonId; } hide: function() { $get(this.buttonId).style.display = 'none'; }

Not only this makes your code more generic, but in ASP.NET is essential. ID’s for server controls can easily be changed if they’re dropped inside some container. You’ll want to pass the ClientID property of the button you want to hide to the class above, and not the actual ID.

DO remember that Javascript is a functional and dynamic language, and use that to make your code more readable.

Functions can be passed around as data in Javascript. Properties and methods can be added to any object. You can misuse these features, of course, but when used correctly they make Javascript a very powerful language. Having classes doesn’t make it C# code! Here’s a StackOverflow thread to get you started on some of Javascript’s less known features.

DO maintain coding standards to your Javascript.

If you want your code to be readable, you need to have standards. Among other things, we use camelCase naming for functions, use underscore prefix to signal “private” members (even if the language does allow them to be accessed outside, the underscore suggest the user of your code to not do so), and use the syntax ‘var arr = [];’ to define an Array (and never ‘new Array()’). What are your standards? Define them, and have everyone follow them.

CONSIDER writing unit-tests for your Javascript.

I admit we’re still taking baby-steps in that direction, but as our code-base gets more and more complex, we’ll have to cover it with unit-tests for it not to break on us. Here are some frameworks recommendations we’re considering to aid us in that.

To conclude, I would like to say that crappy code can be written in any language. If your application is Javascript oriented, it is no excuse to write bad code. The guidelines I have put are nothing new. Mainly, they only remind you to also use them when writing Javascript, and not only in your favorite compiled language.

Add comment
facebook linkedin twitter email

Leave a Reply to dorony Cancel Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



  1. Miky SchreiberApril 7, 2009 ב 23:16

    Hi Doron,

    great post. I linked from my blog.
    One more thing: Many developers think that JS is simple and unimportant part of the project/web site. Therefore, they say, there is no need in JS code review. I think that this is very wrong. As you said, our code can get complex so we have to keep our standarts and write the code in the right way. Code review is a great way to make sure that happens.

  2. doronyApril 8, 2009 ב 15:13

    Thanks, I agree of course. JS code is no different than any other code, and should be code-reviewed and tested in the same manner.

  3. High PR Backlink PyramidSeptember 21, 2012 ב 10:28

    Greetings! I’ve been following your web site for a while now and finally got the bravery to go ahead and give you a shout out from Kingwood Texas! Just wanted to tell you keep up the fantastic work! http://fiverr.com/worldofseo

  4. sacs longchampApril 20, 2013 ב 7:20

    Nobody is going to see you to ultimately mug you in your basement. It’s OK. You can certainly be a youtube star =)