10 JavaScript Quick Tips and Best Practices

JavaScript Quick Tips and Best PracticesRecently, a few blogs and tutorial sites have posted some really good articles on JavaScript tips and best practices, and I thought that was a good topic that could easily be expanded upon. So I put together a list of 10 fairly simple JavaScript tips and best practices of my own.

I tried to include stuff that was not mentioned in those other posts, but I’m sure there is a little bit of overlap. Keep in mind that these are brief tips and recommendations, so I don’t go into great detail about the reasons and such, but I may go into some of them in depth in future articles and tutorials.

In the meantime, please enjoy this list of tips, recommendations, and best practices for JavaScript coding.

1. Use the defer Attribute for IE-Only External Scripts

This is not necessarily a must-do, and neither is it a best practice, but it could come in handy at times. The defer attribute is declared inside of a <script> tag in XHTML like this:

<script type="text/javascript" defer="defer"></script>

The purpose of defer is to tell the externally linked script to wait until the page finishes loading until it runs. The same thing can be accomplished via good unobtrusive JavaScript methods, which usually include code that prevents scripts from executing until the DOM is finished loading.

The advantage of defer occurs in connection with Internet Explorer, since that browser is the only one that supports the defer attribute. So, if you need a quick script to run only in IE, and you don’t mind if the entire page loads before it starts to execute, then simply add defer="defer" in your <script> tag and that will quickly take care of that problem. Fixing a transparent PNG issue in IE6 is one possible practical use for defer.

(Edit 8/3/09: The defer attribute must be used when hiding a script from other browsers with a conditional comment that targets an IE-only script — otherwise the script will run normally in other browsers.)

2. Use a CData Section to Prevent XHTML Strict Validation Errors

Most of the time your scripts will reside in external files, and will be called in a <script> tag either in the <head> of the document, or right before the closing </body> tag.

But there may be an instance where you’re including JavaScript right in the HTML page itself, inside of <script> tags, like this:

<script type="text/javascript">
var my_variable = 100;
if (my_variable < 50) {
  // do something here...

Do you notice the “less than” symbol, which is part of the if statement? That symbol will cause the page to have validation errors, unless you wrap your code in a CData section, like this:

<script type="text/javascript">
var my_variable = 100;
if (my_variable < 50) {
  // do something here...

3. Avoid JavaScript’s Keywords When Creating Custom Identifiers

Many words are reserved as keywords in JavaScript, so you should avoid using them as variable names or other custom identifiers. The complete list of JavaScript keywords is as follows:


4. Avoid JavaScript’s Reserved Words When Creating Custom Identifiers

There are also JavaScript reserved words, which are not necessarily currently used in the language, but are reserved for future use as keywords. Those words are as follows:


5. Don’t Change a Variable’s Type After Initial Declaration

In JavaScript, technically, the following is perfectly legal:

var my_variable = "This is a String";
my_variable = 50;

After the variable’s initial declaration as a string on line 1, on line 2 its value is changed and its data type is also changed. This is not good practice and should be avoided.

6. Don’t Use Global Variables

To prevent possible conflicts, in 99% of cases, use the var keyword when initially declaring variables and their values. This ensures that your variables are localized and are not accessible outside of the function in which they are declared. So, if you happen to use the same variable name in two different functions, there won’t be a conflict since each variable will be abolished the moment its function finishes executing.

7. JavaScript is Case-Sensitive

Remember that the following two variables represent two completely different place holders:

var myVariable = "data";
var myvariable = "more data";

So, use good, consistent practices in your custom identifiers, to ensure that you don’t accidentally declare two different variables when you actually meant to create just one.

8. Use the switch Statement to Handle Multiple Conditions

Don’t do this:

if (example_variable == "cyan") {
  // do something here...
} else if (example_variable == "magenta") {
  // do something here...
} else if (example_variable == "yellow") {
  // do something here...
} else if (example_variable == "black") {
  // do something here...
} else {
  // do something here...

Do this:

switch (example_variable) {
  case "cyan":
    // do something here...
  case "magenta":
    // do something here...
  case "yellow":
    // do something here...
  case "black":
    // do something here...
    // do something here...

The second block of code does the exact same thing as the first — but the second one is cleaner, easier to read, and easier to maintain and modify.

9. Use try-catch to Prevent Errors From Displaying to the User

By wrapping all your code in a try-catch statement, you can ensure that the user never sees an ugly JavaScript error. Like this:

try {
} catch (error) {
  document.write("An error has occured.")

In the code above, I’ve attempted to call a function that doesn’t exist, to force an error. The browser will not display the typical “not an object” or “object expected” error, but instead will display the custom error that I’ve included in the catch section. You could also leave the catch section empty, and then nothing will happen on the client side, or you could create a function to call inside the catch section to handle the error quietly for your own debugging purposes.

Keep in mind that this could cause errors to be hidden from the developer as well, so good code documentation and commenting would be helpful here.

10. Make Multi-Line Comments Readable, But Simple

In JavaScript, you can comment a line of code by putting // at the beginning of the line. You can also comment out a block of code as shown here: /* [code goes here] */. Sometimes you’ll need to include a longer, multi-line comment. A good method to use that is not too visually overwhelming, but is easy to spot in the code is as follows:

 * This is a multi-line comment ...
 * cont'd...
 * cont'd...
 * cont'd...
 * cont'd...

That’s it, 10 easy JavaScript tips and best practices. Hopefully this article has added to the recent “best practices” articles that have been published and promoted. Please offer any suggestions or corrections in the comments, to add to the discussion, as I plan to expand on this in the future.

32 Responses

  1. Mike Grace says:

    Great list of tips for beginners. Easy stuff yet important. Thanks for sharing the knowledge.

  2. Phaoloo says:

    The author must be an experience developer so that he can share these practices. Thanks!

  3. Darko Bunic says:

    Good tips, but sometimes I need to share values from global variable between functions. I’m not sure
    how to do it without global variable … Anyway, thanks for a nice JS collection.

  4. John V says:

    Great article, nice quick tips to keep in mind while coding.

    I believe you have a typo in your “Reserved Words” section – the first word is supposed to be abstract (rather than abtract).

  5. @John V:

    Thanks, corrected. The code highlighter was actually indicating the mistype, but I didn’t clue in.

  6. jerreychen says:

    It’s so good,

    thank you for your sharing.

  7. Richard says:

    Scripts with the “defer” attribute will still run in browsers other than IE – they just run as they’re parsed, rather than waiting for the page to load.

  8. Great post and easy to understand. Thanks for the info :-)

  9. @Richard:

    Thanks for pointing that out. I thought it was clear from the fact that I referred to that heading as “IE only scripts”, but obviously I should have made a note of that. I’ve made a correction to the article to make this more clear.

  10. Lars Gunther says:

    May I correct a mistake. IE is *not* the only browser to support the defer attribute any more. Firefox 3.5 supports it, and in a much better way as wll: http://hacks.mozilla.org/2009/06/defer/

    Re tip 2. You really should not use inline code at all… http://robertnyman.com/inline-code-finder/

  11. Brigitte says:

    thanks for sharing your knowledge!

  12. @Lars:

    Thanks for the heads up on defer in FF 3.5, good to know.

    And my article is not referring to “inline” scripts which are contained inside of HTML markup tags, it’s referring to code inside of script tags withing an HTML page, which is sometimes necessary in specific situations. That’s why the CDATA section is good to know about, because you may one day inherit code or otherwise need to use code within script tags.

  13. Chris says:

    As people have commented above, defer is supported/works great in Firefox 3.5.

    It’s also worth noting that Chrome 2 and Safari 4 fully support defer in the same way, so #1 should really be changed to “Use Defer”.

  14. Kuroki Kaze says:

    Great tips. I want to add “Check your code with JSLint“. For me it saves a lot of time, and helps enforce many of mentioned coding standards automatically.

  15. Alon says:

    nice tips :)

  16. Nilambar says:

    really nice and useful tips. thanks a lot. :-)

  17. siva says:

    Need some book for studying js performance,please suggest me

  18. Lobo says:

    Getting heavily addicted to your site. Thank you.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).