Sunday, April 30, 2006

Six key JavaScript techniques

These are six techniques I have found to be invaluable in my JavaScript/AJAX development. If you are using library like Prototype.js, these techniques will help you better understand what's going on behind the scenes. On the other hand, if you don't want to use one of the pre-baked JS libraries (for example because you are building a very lightweight page, and don't want to incur Prototype's 50K download), then these techniques provide a very lightweight toolkit to make your JS coding more efficient.

Each link below goes to a detailed description with code examples.


1. Optional function arguments
Parameterize your Javascript functions so that some of the arguments are optional, and have defaults if you don't specify a value.
2. Event broadcasting/listening
Make your classes more reusable by broadcasting events. You can bind multiple listeners in the main page to wire your objects together however you like.
3. Namespacing
Increase your code's reusability and maintainability by partitioning your functions and classes into namespaces. If you are programming in Java, you don't put all your classes in the same package, right?
4. Adding functionality to built-in classes
Everything in Javascript is extensible, including built-in types like strings and arrays. Add your own methods to make coding easier and more readable.
5. Object orientation
Utilize closures to create classes and methods with a simple syntax.
6. Try-catch blocks and logging
Use try-catch blocks in your JS coding -- and, more importantly, have something to put in the catch block when something unexpected happens. What do you do in Rails when you catch a runtime error? You write an error to the log. Program with the same robustness in JavaScript!