A quick Javascript formatting tip 10

Posted by Piers Cawley Wed, 16 Apr 2008 09:01:00 GMT

IE’s a pain. The particular pain I want to write about is its pickiness about Javascript object literals. Consider the following Javascript object:

{ success: function () {...},
  failure: function () {...},
}

If you’re used to programming in Perl or Ruby, that trailing comma’s perfectly fine, in fact leaving it there is sometimes considered good practice because it makes it easy to extend the hash, just add a new row and leave another trailing comma.

The trouble is, it’s not strictly legal to do that in Javascript. Pretty much every implementation out there will allow it though.

Except IE.

So, I’ve taken a leaf out of Damian Conways Perl Best Practices and writing my object literals as:

{ success: function () {...}
, failure: function () {...} 
}

By sticking the comma at the beginning of the line, I’m never going to make an object that breaks IE, and adding a new line to the hash is straightforward too. Just stick the cursor in front of the }, type my leading comma, space, attribute name, and hit return when I’m finished.

I’ve also started using the same practice pretty much everywhere else that I’ve got a comma separated list of things:

var foo
  , bar
  , baz
  ;
$.each( anArray
      , function () { ... }
      );

It looks weird at first, but trust me, it grows on you.

Update

In the comments, I make reference to tweaking Steve Yegge’s excellent js2-mode to handle leading comma style a little more gracefully. Since then, I’ve made it work and attached a diff to this issue on the project’s issue tracker.

Comments

Leave a response

  1. Avatar
    Philip Newton about 4 hours later:

    That reminds me of a coding convention I’ve seen for Pascal, where – as in Perl – semicolon is used as a statement separator (rather than as a statement terminator, as – for example – in C).

    So one place put semicolons at the beginning of each line but the first, rather than at the end of each line but the last. (The latter would have been legal in most places, but it would have introduced an empty statement.)

  2. Avatar
    rhesa about 4 hours later:

    reminds me a bit of Perlish coding style (mentioned briefly on PerlMonks by brian d foy).

    Maybe it’ll grow on you, but I think it’s icky.

  3. Avatar
    nicholas a. evans about 12 hours later:
    I’ve been using the same trick when formatting my SQL. e.g:
    select
      a.foo     as a_foo
      , b.bar   as b_foo
      , c.blatz as c_foo
    from
      table1 a
      inner join      table2 b on a.id   = b.a_id
      left outer join table3 c on b.c_id = c.id
    where
      a.foo is not null
      and b.bacon = "chunky" 
    
    ... using the same technique with the join operators and the boolean operators. I’ve found that it not only makes it easier to comment out a line or add a new line, but it also makes it easier (for me) to read than most other SQL formatting techniques. It’s still mildly annoying whenever you deal with the first item in the list though: you need to make sure to remove that leading join operator (comma, etc). If I’m editing the query a lot, I’ll add a “dummy” item to the front, just to alleviate that specific pain. e.g:
    where true
      and a.foo is not null
      and b.bacon = "chunky" 
    

    But I haven’t used this style as comprehensively as you have (“pretty much everywhere else that I’ve got a comma separated list of things”), or as the Perlish coding style… yet. :-)

  4. Avatar
    Piers Cawley about 12 hours later:

    The ‘Perlish coding style’ is definitely a misnomer and also barking mad. If you have leading punctuation on every line, then you start to lose the differences. If you keep your semicolons as statement terminators, then the presence of a , tells you that the new line is in some sense a continuation of the previous line. Same goes for things like:

    clone[property] 
      = YAHOO.lang.isObject(source[property])
        ? deepCopy(source[property])
        : source[property];

    symbol on the first non-blank column? This line is a continuation of the previous one. Leading semicolons would break that rule.

    It’s definitely weird the first few times you see it, but it doesn’t take long before code that doesn’t follow this convention starts looking odd.

    Now, if I can just persuade Steve Yegge’s excellent js2-mode.el to get the indentation right first time when I’m writing javascript in this style…

  5. Avatar
    Asbjørn Ulsberg about 24 hours later:

    I use this coding convention in SQL, because it’s possible to vertically align stuff so it looks neat, but with all other languages I think it just looks strange.

    I’ve tried to write code like that in every C-inspired language I’ve ever written, but it has never grown on me and it probably never will. I just don’t like it. :-)

  6. Avatar
    Eric Suen 1 day later:

    Hi, you should try Spket IDE, Its JavaScript editor has an option “Report Unnecessary Trailing Comma”, and it has a very powerful JavaScript formatter which has an option “remove unnecessary trailing comma”...

  7. Avatar
    Brian Dillard 1 day later:

    This convention was a lifesaver back in the days before there were any decent IE debugging tools I used it for years when I was a JavaScript soloist. But when I started working on large teams at Fortune 500 companies, everybody else freaked out on me about it and I had to stop. Luckily, I’m back to projects where I work on my own and can follow any coding convention I wish.

  8. Avatar
    Piers Cawley 1 day later:

    @Eric: Thanks, but I have 20 years of Emacs; I’m unlikely to go changing now.

    @Brian: Dang! So I’m not original. I’m still in the process of retraining my fingers.

  9. Avatar
    Bjorn 23 days later:

    Can I just say… eeewwh! So instead of remembering a simple syntax rule, you make all your code look crappy? I’m guessing your indentation is equally ‘creative’... (thank goodness Python saves us from much random code vomit like this!)

  10. Avatar
    Piers Cawley 25 days later:

    Well, you can say it, but it does leave the rest of us to wonder what publicly insulting somebody’s taste (and de gustibus non est disputandum and all that) is supposed to contribute to a discussion.

    I suppose I should be grateful that you haven’t also inferred from my post that my momma wears army boots. Or maybe you did, but were too polite to mention it.

Comments