20
Apr

JavaScript is an extremely powerful and flexible scripting language. Unfortunately flexible, for many people, means fallible. I am going to highlight 5 best practices that you can use in any JavaScript project. These are very broad, I will follow up soon with more specific best practices.

First and foremost, keep your code simple, clean and well documented. This is by no means unique to JavaScript but many people seem to think it is the exception to the rule. Your code should naturally comment itself but it is also important to at least introduce every function. I recommend two versions, a fully documented and formatted version and then a compressed version that you use in production. There are a number of free online utilities that can strip out comments and pack your script. There is no need to push out the extra size required for the documentation and formatting.

Second, keep your JavaScript in an external file. The only exception to this rule is if you have some very lightweight script specific to a single page or are setting up variables that cannot be done in the external JS. An external file results in greater scalability, maintainability and degradability. The correct way to reference an external JS file is as follows:

<script type="text/javascript" src="script.js"></script>

Third, separate your JavaScript from the presentation layer. We have all heard of unobtrusive JavaScript but we still see inline script all the time. Instead of cluttering your font-end code with dozens of event handlers add them dynamically. There are exceptions to this rule so please use common sense and separate the layers when it makes sense. An example of adding an onclick event handler from JavaScript:

var div = document.getElementById('div');
div.onclick = new Function("processClick(this)");

Fourth, properly define and scope variables. Many of the scripts I download hoping to use in a project I immediately throw out. The reason being that the programmer did not take the time to properly define and scope variables. Always reference the first instance of a variable by using var. Otherwise the only way someone can know if that is the first reference to that variable is by starting at the top and reading all the way down. It is also important to scope variables correctly. Don’t scope a variable on the global level unless you need it there. I also recommend differentiation of global and local variables though some kind of visual identifier such is all caps on global variables or some easily identifiable character.

Fifth, don’t assume JavaScript support in the first place. Depending on your audience you may choose to disregard this suggestion but for mainstream websites I highly suggest coding with the minority in mind (an estimated 5-10% of web users do not have JavaScript enabled) and degrade your scripts gracefully. JavaScript should be considered as an added feature and not a dependency. An examples of this would be links, the most fundamental element of a web page.

<a href="javascript:processClick()">link</a>
<a href="#" onclick="javascript:processClick()">link</a>

If the user clicks the either of the links above with JavaScript disabled nothing will happen. However, with the code below they could still navigate.

<a href="link.html" onclick="processClick(); return false;">link</a>



7 Diggs Spread This

22 Responses


The very last code snippet uses inline Js. You should have a 100% HTML link, and then in your .js file, a code like the one you provide in the Third part of this post.

It’s like you say something in the Third part, and do the opposite at the end of the last part :p

Louis on 20 Apr 2008 at 1:54 pm

@Louis: quoting from the post: “There are exceptions to this rule so please use common sense and separate the layers when it makes sense.”

Calaelen on 20 Apr 2008 at 2:00 pm

Thanks for the input Louis. Regardless off how the event handler gets there the principle is the same. Consider the last snippet as rendered code after the JavaScript fires if you like. However the third part also states to dynamically add the events when it makes sense, sometimes it simply does not in the context.

Michael on 20 Apr 2008 at 2:07 pm

Thanks Calaelen & Michael for sharing your point of view.

Would you have an example of a situation where it doesn’t make sense to add event in the .js file ?

Louis on 20 Apr 2008 at 2:42 pm

Sure, there are a few situations when I would code JS inline. One scenario would be when you are dealing with a server-side language like PHP/Java/etc and need to pass a server-generated variable to a JavaScript function.

Michael on 20 Apr 2008 at 3:05 pm

@Michael… so you’d agree that it’s completely unnecessary here then?

Oliver on 20 Apr 2008 at 3:23 pm

I am not one to say always one way or another. When it is possible and makes sense I highly recommend it. I wish it was always practical and feasible to keep all JavaScript separate but in the real world it simply isn’t. It is in my opinion a “best practice” and as such we should try our best to incorporate into our code.

Michael on 20 Apr 2008 at 3:38 pm

@Michael: Thank you for this explanation, I woudn’t have thought of this usage.

Though, as you say then, I too think that in a well organized environnement, all Js should be separate from content.

Louis on 20 Apr 2008 at 4:16 pm

Sixth: Use JQuery ;-)

fabian on 20 Apr 2008 at 4:57 pm

In the first best practice you mentioned to maintain two files one as normal version with clean documentation and second one as compressed one.
The problem with online compression tools is that you need to maintain your compressed code whenever you make any changes to your original version. Instead you can use something like YUI compressor. This allows you to compress your javascript file during build time (if you integrate with your ant build script). So you don’t need to worry about maintaining your compressed version all the time.

Parthiban on 21 Apr 2008 at 3:28 am

seventh : Use script.aculo.us if possible ;)

Kevin on 21 Apr 2008 at 3:40 am

@Parthiban

For developers that are using Eclipse based IDEs, I have come up with a solution for this problem. Go to the page

http://rockstarapps.com/pmwiki/pmwiki.php?n=JsLex.JsLex

and you will find a plugin that makes it simple to compress JavaScript files (And rebuild them if you change a file), refactor HTML files to export JavaScript.

digitalIchi on 21 Apr 2008 at 7:32 am

@Parthiban - Absolutely. I am a fan of the YUI compressor and it is great if you are constantly pushing out new builds. Although, for small projects or fairly static scripts, using an online compressor is definitely the easy way to go. I will try and put up an article soon comparing the different compression methods available. Thanks for the link digitalIchi, I will try it out.

Michael on 21 Apr 2008 at 8:02 am

Related to item #4, I would like to add:

Create a namespace for your package.

good face on 21 Apr 2008 at 9:33 am

<strong>5 JavaScript Best Practices…</strong>

5 JavaScript Best Practices…

roScripts - Webmaster resources and websites on 21 Apr 2008 at 11:15 am

Jquery beats easily script.aculo.us. jm

Insane on 21 Apr 2008 at 5:59 pm

[...] Enlace: JavaScript Best Practices [...]

Prosys » Consejos para tener un buen código Javascript on 22 Apr 2008 at 12:02 pm

Good tips. Thanks.

mark on 27 Apr 2008 at 11:11 am

[...] 5 JavaScript Best Practices [...]

CadizCreativa.ES » Blog Archive » Consejos para tener un buen código JavaScript on 04 May 2008 at 9:42 am

Well nice tips but mostly they are general for programming .

Johny on 03 Jun 2008 at 9:09 am

Hi Michael, its great javascript code, but i cannot add phone number form validation. Can you help me?
thanks

Susiana on 14 Jul 2008 at 4:28 am

@Susiana - Looks like you posted to the wrong entry. Shoot me an email for help.

Michael on 15 Jul 2008 at 6:30 pm
Trackback URI | Comments RSS

Leave a Reply

Subscribe to RSS Feed
Powered by FeedBurner
Recent Links
Tag Cloud