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 2 of 3 1 2 3
    1. Hey nice tips, nice to know that i am following almost half of them.
      Like using {} for empty objects, using JSLint, using [] for array, always making use of {} for conditions , love to use raw JS try to implement things in raw JS which people are using as plugins with jQuery, using === and few more….
      Thanx to James Padolsey and Douglas Crockford for gr8 inspiration.

      Love to watch video of presentations of Douglas Crockford and other JS videos from YUI Theatre (Go thru them, they are nice and informative). If you are new they are quiet helpful.

      Where is 16 ??

    2. Russ Back says:

      Great article – thanks. Just a question on declaring Objects and Arrays. What’s the issue with new Object{} as apposed to object literals? I’ve tended to use the former as it’s more consistent with ActionScript and therefore easier to switch between the two. Be good to understand why {} and [] are best practice though.

    3. Henrik Hjelte says:

      About nr 9. Commenting code. If you feel the need to comment the code as you do, it is a sign that you need refactoring. I’d suggest do one or two of this instead:

      A. Put it in a good named function. An added bonus is that it shows up in for example the Firebug profiler. In your case the function could be called logArray or printArray or debugLogArray. That makes the comment obsolete, and the code self-documenting.

      B. Reduce the trickiness. The example you have is quite simple, but I think the for loop is verbose. There are two new variables and four or so expressions. Why not use some library and a function for iterating over arrays?
      I’d think this is clearer and less bug prone:
      somelib.each(array, console.log)
      Replace somlib and each with your own choice.

      • kel says:

        Yes – commenting a for loop that outputs a string on each iteration isn’t necessary and adds verbosity and whatnot. Comments aren’t to explain what is happening (necessarily). They are chiefly to explain *why* you did something (exceptions abound). Furthermore, I prefer them in conversational tone: “next, we need to be sure that this hasn’t already been set….” something like that. That tone will bring comfort to those who follow you and digest your code.

        • Jeffrey Way says:
          Author

          Yes – I’m aware of that. This was just a simple example to demonstrate the idea. Obviously, commenting a simple for-loop isn’t necessary.

    4. Gerrit says:

      Nice list!
      You could also combine #8 and #21 to avoid global variables by putting all code that goes together in the same function scope:
      (function(){
      var name = ‘Jeffrey’;
      var lastName = ‘Way’;
      var doSomething = function() {…} ;
      console.log(name); // Jeffrey — not window.name
      })(); // semi-colon, remember #17 :)

    5. emonweb says:

      Thanks author. Some gr8 tips. anyway 16 is missing.

    6. Ben says:

      I’d say, a good advice for beginners would be to not go too fast into frameworks like jQuery. Because it might lead to confusion.

    7. Nick Tulett says:

      #2

      For example – to avoid using eval for dynamic function names

      Eval
      // Call the function
      result = eval(“test” + i + “();”);

      Not Evil
      // Call the function
      result = window["test" + i]();

    8. DemoGeek says:

      Avoiding the “new” keyword…any other obvious reasons other than that it reduces some verbose typing? It’s pretty much engraved in mind from those old OOP days to use “new”. Wanted to see if it’s worth to get rid of that notion from mind.

    9. As usual, excellent advice. As mundane as #24 sounds, I still do it…Old habits die hard!

    10. Great list! Thank you dude.

    11. Thanks, very helpful and informative, picked up a few things I never even thought of.

    12. Amazingly helpful! Thanks a lot I learned so much.

    13. Mike says:

      absolutely love it!

    14. Very helpful, great tips, thanks!

    15. Teachmeter says:

      I’m new to JS but shouldn’t there be a name = ‘name’ instead of name: ‘name’? I don’t know for sure but just want to ask it.

    16. Kramii says:

      #7 is brilliant – I would never have thought of it.

      I’m not sure I see the benefit of #15, though.

    17. Coby says:

      where is #16? should it not be “23 javascript best practices for beginners?”

    18. Maryam says:

      tnx :)

    19. Brien says:

      Extremely helpful post. I’m surprised there were this many comments without a grammar cop busting you on #22: “…can always…” Those two words are mutually exclusive. I something can happen, it doesn’t always happen.

    20. mr mister says:

      I knew most of them already!!!!

    21. kareemkarawia says:

      nice tutorial
      thanks alot

    22. If you have to comment your code it is time to refactor.
      Extract methods an name them properly, have a good controller function and no need for comments. The only place I would use comments is if I have complex algorithms or complex regular expressions.

    23. Magnus says:

      Number 16 is missing.

    24. Bob says:

      16. Don’t assume that document elements exist.

      Bad:

      document.getElementById( ‘myLabel’ ).innerHTML = ‘Some wonderful text’;

      Better:

      var element = document.getElementById( ‘myLabel’ )
      if ( element && ( ‘innerHTML’ in element ) ) {
      element.innerHTML = ‘Some wonderful text’;
      }

    25. Bob says:

      #6 should really be worded as “Define variables outside of For Statement”

      Declaring is not the same as defining.

      also…

      Use local variables in For Statement is really important.
      For example, in #18, you have:

      for(key in object) {

      instead of:

      for(var key in object) {

      which means that key is a global variable.

      In #19, you have:

      for(x=5000; x > 0; x–){}

      instead of:

      for(var x=5000; x > 0; x–){}

      What does this mean for your benchmarks?

    26. RC Roeder (evil programmer) says:

      Yes evals are evil..but sometime needed. I never discount anything.

    27. Nathan says:

      When possible traverse the array backwards. The comparison to 0 is faster on all architectures than to a variable.

      var container = document.getElementById(‘container’);
      for(var i = someArray.length – 1; i >= 0; i–) {
      container.innerHtml += ‘my number: ‘ + i;
      console.log(i);
      }

    28. Eric Jablow says:

      For #6, adopting Bernard Haussner’s idea above:

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

    29. Mahin Gupta says:

      Thanks… Great tips…

    30. Douglas Holt says:

      In the Better section of #13 shouldn’t

      lastName = ‘Way’,

      be

      lastName: ‘Way’,

    31. Jack says:

      Great! I always use ==, next time, === will be my first choice

    32. daniel lopes says:

      Don’t agree about eval and especially with Short-hand, short-hand should be used when you have only one command after the if statment.

      Eval is not so bad like you said. Obviously you will not evaluate something that user type in a textfield but can be used in many situations without security issues, remember, JS is client-side so everything can be manipulated doesn’t matter if it is evaluated or not because we allways validate the things that should be maintaned in the server side.

      Only care with performance when it is a problem, I will not do a for instead of each before this each starts to be slower than should be.

    33. Florim Maxhuni says:

      O thenks

    34. ryan bost says:

      Great article. I’ve been coding javascript for years and I learned some new things from the article as well as the comments.

      One thing I really liked that no one mentioned however, was the Roadhouse quote in the about the author section. :)

    35. Nice thanks for the tips, good tutorial!

    36. Samuel says:

      Really Good.. thanks Jeffrey!!

    37. san1t1 says:

      JSLint your code, and accept NO errors. This will force you to write it more safely, and will cover a good number of these ‘best practices’

      JSMin-ify it. Remove all new lines. Anyone who thinks you don’t need curly braces will quickly get unstuck.

      Have a script that does both of these and deploys your code (even if just to a different folder) before you test it.

      Comments are for lengthy procedural scripts, regex and hard-to-read algorithms. Sensibly factored programs need less comments. That said, if you’re in a team, JSDocs are good, especially if you all use IDEs that support them, and your code base is BIG.

      Also if you’re writing code that someone else will end up maintaining, remember it’s often worth sacrificing “clever” code for maintainable code, even if there’s a small performance loss.

      Use a library (jquery and jquery ui the clear leader) to manipulate the DOM. Code that doesn’t touch the DOM, write in straight Javascript.

      Don’t pollute the global namespace.

    38. Anthony says:

      If you don’t put semi-colons after functions like

      var foo = function() {
      };

      then you should not use semicolons anywhere for consistency. It’s about time js became more python-like.

    39. Nad e Ali says:

      i think you miss one more thing that is cache your DOM object instead of calling many time
      like

      bad
      function testFunction(){
      document.getElementById(‘testElement’).className=’testClass’;
      document.getElementById(‘testElement’).value=’test’;
      document.getElementById(‘testElement’).disabled=true;
      }

      better

      function testFunction(){
      var testElement=document.getElementById(‘testElement’);
      testElement.className=’testClass’;
      testElement.value=’test’;
      testElement.disabled=true;
      }

      btw very nice Article

    40. Abhilash says:

      Just Great.
      Just Great.
      Just Great.

      Thank You for this nice one.
      :-)

    41. Bean Taxi says:

      This borrows VERY heavily from Douglas Crockford’s book, blog, web site etc — I think about 20 of the 24 are Crockford’s. It’s fair to say without Douglas Crockford this list wouldn’t exist. Yet there is very little in the way of attribution. I doubt that’s malicious, but it’s not great form.

      Btw I’m not a Crockford zealot. I don’t know the man, and I disagree with some of his practices (e.g. declaring all vars at the beginning of a function). But fair’s fair.

      • I agree with Bean Taxi. I just picked up the Best Parts book yesterday. In trying to find a better explanation for Doug’s preference to using array literals vs the constructor, I ran across this site; and was surprised to read how much is basically Doug’s book.

    42. Ben says:

      Wow! Fantastic Article!!! Thanks Jeffrey!

    43. Evan Larsen says:

      Wow, I’m so proud that I have been using most of these practices and I’ve also learned a few more, thanks!

    44. Jomit says:

      Excellent compilation Jeffrey !! Thank you very much . . . .

    45. Souvik says:

      Thanks.
      Greatt post

    46. Shane Strong says:

      Perfect post for a beginner like me thanks for the incite on good practice.

    47. mahdi says:

      In My Opinion this is the fastest way to do it .
      there is no problem to put the variables inside of the forloop so you could put it out side or inside this doesn’t change the speed .
      if the pushing the result in array is faster than storing them in a variable .

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

      let me know if you guys have another opinion !

    48. Sambath says:

      best practice is very useful for me. to increase my quality in the project.
      Thx

    49. uma mahesh varma.seeram says:

      very nice post and it helps alot for beginners

    50. Nishit says:

      thats was a great article indeed.. thanks mate..

    Comment Page 2 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.