Three more things you should not do in JavaScript

On the Yahoo! user interface blog I just saw their post “with Statement Considered Harmful“. Good advice.
Here are a few more things that I never do in JavaScript:
- Never use the “with” statement (as described above)
- Never use single line “//” comments. Use “/**/”. One day your code is going to be mangled and the newlines removed (perhaps by a crappy content management system), and suddenly your code will be commented out.
Before:
// a comment alert('ping!');After: (UH OH!)
// a comment alert('ping!'); - Never omit the semi-colon after a statement. Again, this is to protect your code in case the newlines are removed, and to make the code easier to parse (by humans and machines).
Before:
var t = 'ping!' alert('ping!')After: (ERROR)
var t = 'ping!' alert('ping!')This can be harder than it seems! For example, in the following example you should add a semi-colon after the closing brace:
var myFunc = function() { alert('ping!'); } - Never omit the optional brackets { } around a statement. This can prevent some hard-to-debug errors when you add and remove code.
Before: (MISLEADING INDENT!)
if (true) alert('ping!'); deleteItem();Fixed: (UNAMBIGUOUS)
if (true) { alert('ping!'); } deleteItem();
To check your code for missing semicolons and brackets, use JSLint.