Three more things you should not do in JavaScript

see-no-evil.jpg

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:

  1. Never use the “with” statement (as described above)
  2. 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!');
  3. 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!');
    }
  4. 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.

Leave a Reply