- Always use semicolons. Implicit semicolons (in JS) are a horrible idea, especially with some of the interesting syntax floating around in common usage. They are also generally required by any JS minifier.
- Avoid eval()Avoid eval(). This causes all sorts of problems, and is a very quick way to slow down your application. Most uses are actually abuses. Every time you think you need to use
eval()
, double and triple check for another way; there is almost always a cleaner, easier way unless you are actually trying to execute an entire string worth of JavaScript. (function() {/* stuff */})()
is a good way to encase a set of code and create a local scope for it. Using objects is another, often better, way; objects are more analogous to namespaces in other languages when used in this way. Just watch out forthis
. Unlike most other languages,this
doesn't always reference what you might intuitively think it does. Also remember that unless otherwise specified all JS variables, functions and other objects are all global, even across multiple.js
files.- Find and learn/use a good JS library. jQuery is one of the more popular ones. These will do a lot of the heavy lifting for you including things like feature detection and abstracting away DOM manipulation and the multiple ways different things have been implemented in different browsers.
- Always use semicolons. Seriously. Get an IDE that warns you when you forget them. I don't want to sound ranty, but there's been a few times where bugs have been introduced just for the lack of a semicolon and the browser won't warn you about these.