Skip to main content
3 of 4
broken link fixed, cf. https://meta.stackoverflow.com/a/406565/4751173
Glorfindel
  • 3.2k
  • 6
  • 26
  • 33
  1. 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.
  2. 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.
  3. (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 for this. 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.
  4. 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.
  5. 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.