Top 10 “Must Follow” JavaScript Best Practices

JavaScript went on to become cult right after its launch due to its extensive list of features. It also gave programmers the chance to give their webpages a more eye-popping look and website visitors were happier than ever.

Despite the large number of developers that sing the praises of JavaScript, there are those Internet users who see its dark side.

Webpages using multiple JavaScript codes are slow to load and overuse of JavaScript contributes to making webpages look cluttered and ugly. In no time the smart use of JavaScript became a hot topic amongst programmers.

Without further ado, let us dive into our list of JavaScript best practices that will save you from this unwanted criticism.

Keep it short, stupid!

You have read this a zillion times already. As a programmer/webmaster you might have applied this tip multiple times too but never forget this in case of JavaScript.

  • Use comments and white spaces while in development mode to keep your code readable.
  • Remove white spaces and comments before publishing your scripts in live environment. Also, try to shorten your variable and function names.
  • Consider using third party tools to compress your JavaScript code before publishing the same.

Think before you touch object prototypes

Appending new properties to object prototypes is one of the most common reasons for script failures.

yourObject.prototype.anotherFunction = ‘Hello’;
yourObject.prototype.anotherMethod = function () { … };

In above case all variables will be affected as they are inherited from “yourObject”. Such usage might cause unexpected behaviour. Henceforth, it is suggested to delete such modifications right after its usage:

yourObject.prototype.anotherFunction = ‘Hello’;
yourObject.prototype.anotherMethod = function () { … };
test.anotherMethod();
delete yourObject.prototype.anotherFunction = ‘Hello’;
delete yourObject.prototype.anotherMethod = function () { … };

Debug JavaScript Code

Even the best programmers make mistakes. To limit them, run your JavaScript code through a JavaScript debugger to make sure that you haven’t made any silly blunders that can easily be prevented.

Avoid Eval

Your JavaScript can work well without the use of “eval” function. For those not aware, “eval” gives access to JavaScript compiler. If a string is passed as parameter of “eval” then its result can be executed.

This will degrade your code’s performance though it acts as a boon during development phase. Avoid “eval” in live environment.

Minimize DOM access

DOM is one of the most complex APIs that slows down the code execution process. At times the webpage might not load or it might load incompletely. Better to avoid DOM.

Learn JavaScript before using JavaScript libraries

Internet is chock full of JavaScript libraries that perform various functions. Programmers end up using JavaScript libraries without understanding the side effects of the same. It is strongly advisable to learn the basics of JavaScript before using third party JavaScript libraries; otherwise, be prepared for disastrous results.

Never use “SetTimeOut” and “SetInterval” as alternatives to “Eval”

setTimeOut( “document.getID(‘value’)”, 3000);

In above code document.getID(‘value’) is used as a string that is processed within the “setTimeOut” function. This is similar to “eval” function which executes a string during every execution of code thus degrading performance. Henceforth, it is suggested to pass a function within such functions:

setTimeOut(yourFunction, 3000);

[] is better than “new Array();”

“A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object.” – Douglas Crockford, writer of JavaScript: Good Parts.

Suggested:

var a = [‘1A’,’2B’];

Avoid:

var a = new Array();
a[0] =  “1A”;
a[1] = “2B”;

Never use “var” multiple times

While initializing every variable programmers tend to use “var” keyword. Instead, it is suggested that you use commas to avoid redundancy of keywords and reduce code size:

var variableOne = ‘string 1’,
variableTwo = ‘string 2’,
variableThree = ‘string 3’;

Never Miss Semicolons

This is one of the programming bugs that can consume hours of debugging. Personally, I have spent hours looking for problems in my code when the reason was the missing semicolon.

I am pretty sure that you must have read most of the above points but at times we tend to ignore the basics. Did you ever miss a semicolon? Has “eval” keyword messed up your code’s performance?

SHARE THIS POST
  • http://www.profeval.com Anonymous

    The next to last point related to “var” actually hinders readability.

    I recommend using a JavaScript minifier , and something like Google’s closure compiler, to compress your JavaScript. It automatically rolls multiple “var”s into one.

    • Dan

      It’s not a space issue. Multiple vars scattered across a function actually threaten scope integrity. Using a single var statement at the beginning of the function makes sure to avoiod that. It doesn’t hinder readability once you get used to it. Besides, JSLint will pin-point the “subtle bugs” Bryan was referring to.

  • http://www.scruffles.net/ Bryan

    I’d rather see a keyword repeated a few times and have it ripped out by the minifier than have to deal with subtle bugs like this:
    var variableOne = ‘string 1′,
    variableTwo = ‘string 2′;
    variableThree = ‘string 3′;

    • http://SalmanSiddiqui.com Salman Siddiqui

      People seem to have already appreciated your comment. I agree, it is one more type of blunder that few of us have done. This is the reason why I suggest people to break down code and make it look as clean as possible. It might increase the length of code but it then the code does explain things all by itself.

  • http://www.poetro.hu/ Poetro

    Could you describe why it is a bad thing to modify the prototype? Because it was not clear. And another thing, why do you add the above methods above to the prototype and not the test object itself, if you only use it on that one, or if you need that function to apply only to that object why don’t you use apply() or call()? That will make the function be reusable and also it doesn’t have to be created every time you need it.

    • http://SalmanSiddiqui.com Salman Siddiqui

      Poetro – There are multiple ways to approach a solution in programming. I had seen examples where programmers would end up confused with their own Object Prototypes and henceforth I suggested to rather delete what is not in use. It just eradicates any possible confusions.

      Also, I try to break down my stuff as much as I can. Two reasons:
      1. It makes the code look clean which is really important.
      2. It makes the program lengthy which forces people to believe that I have written a really complex code! [just kidding] :)

    • Junrie

      You’re Correct!!!!!!!

  • Jonathan

    var variableOne = ‘string 1’,
    variableTwo = ‘string 2’,
    variableThree = ‘string 3’;

    dont like :/

  • http://SalmanSiddiqui.com Salman Siddiqui

    Thanks! Will check those out.

    But, I am just praying that HTML5 starts taking over JavaScript from all corners. Least number of programming language integration in one program is what I love to do… #dream

    • Junrie

      Where you study in College Siddiqui??? are you a Programmer???

  • http://www.logodesignstemplate.com/gazette/ Community Wordpress Theme

    Very useful post! thanks for posting:)

  • http://artbyjb.com Jeffrey Bennett

    I’ve definitely had my fair share of debugging issues when the only problem was a missing semicolon. It can be frustrating, but it also taught me to be more careful when I code.

  • http://www.evelt.com/ Joel Klein

    thanks,
    this website is beautiful too

  • http://nefariousnewt.blogspot.com NefariousNewt

    On comments: NEVER remove them. I’ve done a fair share of maintenance programming in my life, and there is no greater waste of time than having to figure out what someone was trying to accomplish with a chunk of code and having nothing to go by but variables names and badly-formatted code. If you write tight, legible code, a few extra lines of commentary isn’t going to degrade performance that much and you will have saved someone many hours of frustration.

  • http://ecommercesoftwarereviewss.com/ ecommerce reviews

    Wonderful post! I agree with you but i have some opinion also. In my opinion, it is depends upon the style of the programmer use. I know that to validation the page, we can also used the Java script to improve it’s functionality. May be possibility that some function like ‘eval()’ created the load to load the webpage.
    I will try to use this function and write the own idea about it . I hope to present of this type of the post in the future also.
    Thanking you.

  • Gazurtoid

    I agree with Bryan. var should always be used when declaring a variable to maintain structure.

  • http://www.facebook.com/zapetin52 Zapetin Alejandro

    good post!… but i think there are more tips!!

  • Junrie

    I appreciate your top 10 ” Must Follow” Javascript Best Practices.I also conclude that it is very useful to me as a programmer.I also thankful to the authors of these website.
    !!!!!That’s all thank you for your information about the javascript language.

  • Junrie

    Your the author of these site salman???