views:

1183

answers:

11

What are some good resources to learn best practices for Javascript? I'm mainly concerned about when something should be an object vs. when it should just be tracked in the DOM. Also I would like to better learn how to organize my code so it's easy to unit test.

+1  A: 

Probably the single most important thing is to use a framework, such as jQuery, or prototype, to iron out the differences between browsers, and also make things easier in general.

Cebjyre
+5  A: 

I liked JavaScript:The Good Parts by Douglas Crockford although it's focused entirely on the language and ignores the DOM altogether.

slm
+1  A: 

This.

Will
+1  A: 

You can pick up a lot from Pro JavaScript Techniques, and I'm looking forward to Resig's forthcoming Secrets of the JavaScript Ninja.

Hank Gay
+25  A: 

Seconding Javascript: The Good Parts and Resig's book Secrets of the Javascript Ninja.

Here are some tips for Javascript:

  • Don't pollute the global namespace (put all functions into objects/closures)
    • Take a look at YUI, it's a huge codebase with only 2 global objects: YAHOO and YAHOO_config
  • Use the Module pattern for singletons (http://yuiblog.com/blog/2007/06/12/module-pattern/)
  • Make your JS as reusable as possible (jQuery plugins, YUI modules, basic JS objects.) Don't write tons of global functions.
  • Don't forget to var your variables
  • Use JSlint : http://www.jslint.com/
  • If you need to save state, it's probably best to use objects instead of the DOM.
Ryan Doherty
+1 thanks for the singleton link, it's the 1st time I understand how to do it in JS in an easy to read/understand article.
Marco Demajo
+4  A: 

I disagree to the "use a framework" statement to some degree. Too many people use frameworks blindly and have little or no understanding of what's going on behind the curtains.

thomask
A: 

this article (with comments) is also very helpful :

http://www.dustindiaz.com/javascript-no-no/

Canavar
+1  A: 

As an addendum to the Crockford book, you may also want to check out this piece Code Conventions for the Javascript Programming Language. I also have a slightly different suggestion: instead of using a JS library off the bat, why not create your own? You may write a crappy library (as I did), but you'll learn something in the process. You have existing examples you can use as models. Also, to help give you an understanding of JS design patterns, I shall recommend another book, 'Pro Javascript Design Patterns'.

bobtorp
+1  A: 

YUI Theatre has a bunch of videos (some with transcripts) by Steve Souders, Douglas Crockford, John Resig and others on JavaScript, YUI, website performance and other related topics.

There are also very interested google tech talks on Youtube on jQuery and other frameworks.

dplante
+1  A: 
OscarRyz