Just A Summary : Tag tips, everything about tips http://bofh.org.uk/articles/tag/tips.rss en-us 40 Piers Cawley Practices Punditry A quick Javascript formatting tip <p>IE&#8217;s a pain. The particular pain I want to write about is its pickiness about Javascript object literals. Consider the following Javascript object:</p> <div class="typocode"><pre><code class="typocode_default ">{ success: function () {...}, failure: function () {...}, }</code></pre></div> <p>If you&#8217;re used to programming in Perl or Ruby, that trailing comma&#8217;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.</p> <p>The trouble is, it&#8217;s not strictly legal to do that in Javascript. Pretty much every implementation out there will allow it though.</p> <p>Except IE.</p> <p>So, I&#8217;ve taken a leaf out of Damian Conways <cite>Perl Best Practices</cite> and writing my object literals as:</p> <div class="typocode"><pre><code class="typocode_default ">{ success: function () {...} , failure: function () {...} }</code></pre></div> <p>By sticking the comma at the beginning of the line, I&#8217;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 <code>}</code>, type my leading comma, space, attribute name, and hit return when I&#8217;m finished.</p> <p>I&#8217;ve also started using the same practice pretty much everywhere else that I&#8217;ve got a comma separated list of things:</p> <div class="typocode"><pre><code class="typocode_default ">var foo , bar , baz ; $.each( anArray , function () { ... } );</code></pre></div> <p>It looks weird at first, but trust me, it grows on you.</p> <h3>Update</h3> <p>In the comments, I make reference to tweaking Steve Yegge&#8217;s excellent <a href="http://code.google.com/p/js2-mode/">js2-mode</a> to handle leading comma style a little more gracefully. Since then, I&#8217;ve made it work and attached a diff to <a href="http://code.google.com/p/js2-mode/issues/detail?id=64">this issue</a> on the project&#8217;s issue tracker.</p> Wed, 16 Apr 2008 04:01:00 -0500 urn:uuid:43c91868-fede-47d2-8f9b-14fdce6dee88 pdcawley@bofh.org.uk (Piers Cawley) http://www.bofh.org.uk/articles/2008/04/16/a-quick-javascript-formatting-tip#comments The Practice of Programming javascript formatting tips http://www.bofh.org.uk/articles/2008/04/16/a-quick-javascript-formatting-tip