">

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>

The following two tabs change content below.
Scriptiny is a web development blog featuring fresh articles on JavaScript, AJAX, CSS, XHTML, PHP, Photoshop and more.

Latest posts by Scriptiny Editorial (see all)

  • 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: quoting from the post: “There are exceptions to this rule so please use common sense and separate the layers when it makes sense.”

  • 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.

  • 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 ?

  • 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.

  • Oliver

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

  • 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: 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.

  • 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

    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.

  • @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.

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

    Create a namespace for your package.

  • Pingback: Prosys » Consejos para tener un buen código Javascript()

  • Well nice tips but mostly they are general for programming .

  • Susiana

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

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

  • shubelal

    Hi Michael, great Javascript Code

    thank u

  • Thank you for these advices
    the administrator of http://www.buvetteetudiants.com

  • 8th: Learn to code properly, then the need for heavy frameworks like jQuery or Scapulitios isn’t needed.

    Great article….

  • Very good tips. Yes, I cannot stand it when javascript is placed in an HTML document, or if it is jumbled without documentation.

    And your last tip is also very important. So many users these days actually turn Javascript off. So it is necessary to make sure that your web pages are fully functional without JS.

    In fact, I often try to do everything using CSS, and avoid JS as much as possible.

    Nice article.

  • Hi
    I am Dinesh verma – .NET developer from India with 1+ yr Experience .
    I see your this web. its Nice

    Gr8 And nice Blog for every developer.
    Its nice Michael

    With Best Regards
    Dinesh verma

  • lisheng

    Very Good! 非常棒!
    I come from china!

  • Santosh

    Amazing collection. Your solutions to common requirements are really elegant. Thanks!

  • Pingback: JavaScript Best Practices : Felipe S. Buenaño()

  • Krishna sagar

    Its neat, clean and straight to the point with no fuss.
    keep up the good work.

  • claudegals(JR)

    great work… tnx….

    icotp on ict
    leyte

  • Derrick

    It's never necessary to use inline Javascript. If you need to pass something from PHP to Javascript, you can do so with an AJAX call, or by echoing it into a hidden input field, then retrieving the contents of that field in your external Javascript file.

  • thanks for the information I will consider, it

  • Pingback: fReAkStyLe » Blog Archive » 5 Best JavaScript Practices()

  • Hughes

    great article keep it up

  • sumitvint

    very nice tip for general programming and very helpful for
    <a href="htttp://vintagesos.in">website</a> development .

  • Andy

    Your site rocks!!!

  • Superb article and very informative this is something worth reading not only to students but also to aspirant developers. This is certainly true and must be considered and put into practiced. Thanks for posting and good job!