Writing better Javascript – The Essentials

When I came across Javascript for the first time, it was in the form of a snippet that I put on a page to do some validation. Most web developers start out with Javascript in the same way. Do a little validation here, a rollover effect there , trivial stuff like that. That gets most people started with Javascript on the wrong foot, thinking that it’s a mere scripting aid.

With more and more Javascript code being released on the web, and with more applications relying on Ajax and Javascript effects in a bid to jump onto the Web 2.0 bandwagon, it is really important that people starting out with Javascript are aware of its strengths, weaknesses and quirks before they actually write production code.

So here’s my attempt at making the lives of Javascript beginners a little easier.

Know the Language
Before you can actually write quality code in a language, you have to know it inside out. Fortunately, Javascript is not a huge language to cover. It is hover, very versatile. The expressive power that you have at your disposal when you’re coding in Javascript is amazing. I can ramble on endlessly about how awesome Javascript is, so I’ll get right to the point. The best reference IMO that’ll get you started in the right direction is this 3 part series of lectures by Douglas Crockford. He’s currently a Senior Javascript Architect at Yahoo!, and his lectures are very nicely organized and his delivery style keeps you interested. Also, if you’re interested in the history of the language and the browser wars that played a great part in shaping how we code for the Web today, you’ll love these lectures. Even after sitting through these lectures, I still use the power point slides for quick reference whenever I’m unsure about something.
Sit through these lectures with the intent of learning something and by the time you finish, not only will you be crazy excited about Javascript, you’ll have a solid foundation to begin writing code and building on what you’ve learnt. For me, these lectures have defined how I write Javascript code. The difference between the code I wrote before and after these lectures is staggering. So if you don’t know why you should use === and !== instead of == and !=, or what a lambda or closure is, or how to do prototypal inheritance, I suggest you click here.

Unobtrusive Javascript
If you’re into the whole separation of behavior, content and presentation on the web thing then you’ll know what I’m talking about. If you don’t know what the previous sentence meant, you need to crawl out from your hiding place under a rock. There are many schools of thought on unobtrusive Javascript. I being a firm believer in KISS (Keep It Simple Stupid) have a don’t overdo it approach to unobtrusive Javascript. If it’s helping me out, fine, if a certain thing is too hard to code without having Javascript in the HTML, so be it. Please forgive me my unobtrusive fanatic friends.
So what you basically need to do is write all your Javascript code in a separate .js file. There are many advantages to this technique.

  • All your Javascript is cached in one go, leaving only the HTML to be fetched from the server on each page. (This depends on how you’ve organized your .js files)
  • Code reusability.
  • Easier to organize your code in packages/classes. You can write a controller for each page that will initialize its Javascript components, or better yet, have a base controller which initializes common components and all other controllers inherit from the base controller.
  • Improvement in code readability, no more HTML strewn with Javascript.

Time to write some code. So say that you have an image that has a rollover effect. If you had been coding 5 years ago, you would have done something like this:
<img src="button.gif" onmouseover="this.src='button_over.gif'" onmouseout="this.src='button.gif'" alt="" />

Say you have twenty such buttons all over the page, you’d have to do this to each one of them. Here’s how to do it the unobtrusive way (simplified code):
HTML
<img src="button.gif" class="rollover" alt="" />
Javascript
function activateRollovers(){
var rollovers = document.getElementsByClassName('rollover');
for(var i=0;i<rollovers.lenght;i++){
rollovers[i].onmouseover = function(){
// insert '_over' in image name before image extension
};
rollovers[i].onmouseout = function(){
// remove '_over' in image name before image extension
}
}
}
// call this function when window loads (prototype.js method)
Event.observe(window, 'load', activateRollovers);

CSS class names are most commonly used for the purpose of grabbing elements of a certain type, but there are other methods as well, described in this example of unobtrusive form validation.

Objects and Functions
Everything is an object in Javascript. A function is an object. You can even define a function as a variable. What makes Javascript objects truly unique is that they are essentially Hashmaps. Objects are comprised of name <-> value pairs, where the name is a string and the value is an object. Master the functional aspects of Javascript (functions as variables & objects, passing functions, function pointers), and you’ll be on you’re on your way to Javascript greatness.

Frameworks and Libraries
It is pretty well known that there is no dearth of Javascript frameworks and libraries. The web is overflowing with them. Choosing the right on for your project is the important bit.
But why use a framework at all you say? Javascript has its share of quirks and flaws. And inconsistent implementation and incompatible APIs by browsers doesn’t help either. The extensible nature of Javascript (you can modify built in objects via their prototypes) allows frameworks to provide richer built in objects and cross browser compatible methods. Most frameworks provide Ajax objects, which allow easy communication with the server.
I’ve personally always used the prototype framework. Yahoo!’s YUI has a rich set of UI controls, and is a good choice if your site has heavy Javascript/Ajax UI work. jQuery, mootools and dojo all come highly recommended. Read through Justin’s Top 5 Javascript frameworks list to get a clearer view of the playing field. Although I disagree with his ranking, I found the comments to the post enlightening.

Ajax Patterns
Ajax IMO is a necessary evil. I’d rather work in Flex, or maybe even Silverlight for RIA. (Can’t wait for JavaFX!) But as long as there’s a demand for DHTML, you’re going to have to write Ajax code. There are a gzillion different ways of doing a thing using Ajax, so I highly recommend using Ajax Patterns as a reference for all your Ajax design and coding time decisions. If you’re going to do something wrong, do it right.

Exception Handling
As I’m writing this post on the Posts page in WordPress, Firebug is alerting me to a Javascript error on this page. The web has more Javascript errors than it actually has web pages. Probably. My point is that exception handling is rarely applied in Javascript code on web pages. The fact that Javascript is loosely typed is probably one of the main reasons why programmers get sloppy and don’t feel that their Javascript code needs as much exception handling as their Java/.NET code.
Javascript exceptions in the worst case can render unusable UI on a web page. Using exception handling will allow you to show something like an error message or report bug form in place of the UI, instead of something broken. Or maybe even switch to a non-Javascript UI on an exception. The sky’s the limit.

I hope this rant has set you off on the right foot with Javascript. Treat your Javascript code as more than a code snippet, and your code will be significantly more robust, efficient and manageable.

Advertisements

7 thoughts on “Writing better Javascript – The Essentials

  1. Would using jquery be helpful ? and would it be more efficient ?

  2. If you’re not using any framework at all, than jQuery will be ALOT more helpful. Go for it!
    If you’re comparing it with another framework, then you’ll have to assess based on your needs. For example, Prototype has a better set of objects and methods, whereas jQuery has an extra Effects module. Which is better for you is up to you.
    Overall, they’re equally good.

  3. Osama A. says:

    That’s a great set of resources to get people up to speed — more people need to realize how much potential javascript / ajax has.

    I’d point to Quirk’s Mode, A List Apart and Ajaxian as additional references when debugging browser issues.

  4. Asad says:

    It’s pretty true that Javascript is in use all over and has gained enormous recognition. Gone are the days when you have to think 10 times before using javascript in your applications for the fear of your users not having javascript enabled.

    It’s in fashion nowadays and to do it right, you need to treat it like you treat your back-end programming languages. In the past, it was some messy code, but now it’s time people learn that it’s a powerful scripting language.

    Nice article there 🙂

  5. Obaid says:

    Javascript indeed is the getting popular and gaining visibility quickly. 🙂

  6. […] running on the JVM) partly because of Javascript’s immense expressive power, something that I’ve been ranting about for quite some time now. Can’t wait for Rhino on […]

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: