Wednesday, October 07, 2009

Nicholas Zakas on "Writing maintainable JavaScript"

A great video on JavaScript best practices by Nicholas Zakas at Yahoo!


I think his best suggestions are:
  • don't put JS in CSS; its bad for performance as well
  • don't put CSS in JS; change styles by changing classes, and not actual styles.
  • don't put HTML in JS; this is rather tricky to avoid, but again if the markup changes, its really time consuming to change it in JS. I guess this one depends on whether you have a lot of markup that gets dynamically updated. One way I really like is how Dojo widgets go about this using HTML templates.
  • attach event handlers using JS, not within markup ex. "onclick". This is an odd one, but it really does make sense, what if the JS hasn't loaded when the click occurs?
  • event handlers shouldn't contain business and UI logic; makes a lot of sense since this way I could re-use my event handlers, and I can re-use my business / UI logic
  • don't compare against "null", compare against the type you actually want.
  • don't extend objects you don't own ex. Array and extending it with "indexOf" to fix a bug in IE. (Guilty as charged...)
  • least but not least, throw Errors within functions that can really go bad and you get a useless error like "undefined is undefined". At least now you can tell what went wrong.
Since I have not had enough time to blog about "My thoughts on technology..." I figure I can share videos on others' thoughts on web technology.

No comments:

Post a Comment