Wednesday, April 7th, 2010

Is there something to the crazy comma-first style?

Category: JavaScript

I first saw real usage of “comma-first” JavaScript style via Ryan Dahl of Node.js fame.

My eyes were a little scarred at first, but now we are seeing the reasoning behind it:

Note how the errors pop out in the comma-first style.

The object literal cases will throw, though a final trailing comma will cause errors in MSIE. The missing comma errors are particularly devious when it comes to the var statement, and lists of arrays.

Missing commas in a var statement will cause global leakage, which can make for odd and hard to track-down errors. Pooh on JavaScript for defaulting to global scope unless you use var.

Pooh on JavaScript for using […] to mean both “property access” and “array literal”, but as a result of this poor choice of operator, [[1,2][3,4]] resolves to [undefined], which is quite different from [[1,2],[3,4]].

You code in the language you have. Like English and C, JavaScript is clearly not perfect, but it is widespread, and that is much more important.

Many decry comma-first as being “ugly” or “unclean”. However, this is a statement about one’s brain and habituation, not about the code itself. In my opinion, “clean” is defined as “easier to interpret quickly”. If a given coding convention makes differences look different (especially errors) and another coding convention makes errors harder to spot, then it’s clear that the first is more “clean”. If you disagree, then apparently, “clean” just means “looks like what I saw yesterday and the day before”. This rubric is worse than useless, as it specifically prevents innovation or improvement.

And, regarding “ugly”… ALL code is ugly. Yours, mine, everyone’s. Code Is Ugly. Just face it. When someone says “beautiful code”, hear “beautiful rotten entrails”. The only beautiful code, the most clean code, is no code at all. If it’s there, it’s ugly. The unfortunate fact of software development is that, in order to create beautiful software, we must use ugly code.

The best we can do is make sure that there’s as little code as absolutely necessary, and that it is as reliable and easy to interpret as possible. Conventions must be judged based on these standards. Anything that obscures the intent of the software is by definition “unclean”, and every line of code is “ugly”.

The comment discusses the code below:

What do you think? I am always amazed at how ridged I am with some style, and how I can flip around on others. One random example. I used to very much be a guy who liked the CSS of style="foo: bar; fuz: buz;" but now style="foo:bar; fuz:buz" tickles my fancy.

Whatcha think?

Posted by Dion Almaer at 6:59 pm

3.2 rating from 38 votes


Comments feed TrackBack URI

Inline styles? They’re *always* ugly. :P

The comma-first style is an interesting idea; I can see that it’s quite useful for catching simple errors. Thing is, though, if you run your JS through JSLint or the YUI compressor before deployment (which I think should always be done on production code), you’ll catch these errors anyway. So is it worth writing in what is (to my mind) a somewhat ‘uglier’ style of code? Not really, no.

Comment by barryvan — April 7, 2010

Reminds me of if(i=5) vs if(5=i) for i==5, it makes total sense but we coders will aways be a nasty stubborn bunch :)

Comment by aw2xcd — April 7, 2010

I also saw it for the first time when Ryan requested it as the default format output for node’s pretty printer. I’ve played around with it both ways and think I’d be comfortable with it once I tweak my editor’s indent scripts to work correctly. The main benefit for me is the removal of the tailing comma conundrum. I’m used to the trailing comma being legal from Python, so when I go to add onto the end of an object/array literal I have a tendency to forget to go back and tack on the comma on the line before. I doubt it’ll become canonical everywhere since the JS community is so large and fragmented but I could very easily see it becoming a node.js community quirk.

Of course, it could become a moot issue for me. I’ve shifted over to coffeescript for my personal projects which makes the commas optional for multiline array/object literals.

Comment by grayrest — April 7, 2010

I just have a script I run that checks all code for the sort of commas that break IE. The comma-first convention makes code look terrible and is visually distracting as the first character on the line.

Comment by tmallen — April 7, 2010

I’ve seen the same discussion about placing operators at the beginning of a line. I’m not jumping on that bandwagon. Programmer brains are wired to expect something at the end of a line. I disagree with all code being ugly, that argument doesn’t justify this style. Debugging might, if that’s what you are going for when writing code.

I enjoy reading and working with pretty code the same way can enjoy reading a good book, so I believe there’s such a thing out there as pretty code and we should strive for it as much as possible.

Comment by Jadet — April 7, 2010

Correct me if I am wrong, but if the javascript code is style in comma-first style and not compressed or minified, the js engine would inject semi-colons in the wrong places:

var a = "ape"
, b = "bat"
, c = "cat"
, d = "dog"
, e = "elf"
, f = "fly"
, g = "gnu"
, h = "hat"
, i = "ibu"

//would be interpreted as this
var a = "ape"
, b = "bat";
, c = "cat";
, d = "dog";
, e = "elf";
, f = "fly";
, g = "gnu";
, h = "hat";
, i = "ibu";

Comment by tonyl — April 7, 2010

I often use this style. Besides helping to spot errors as explained in the article, it’s also better for adding or removing elements at the end of the list. Simply add or delete a line. With comma-postfix style you need to make changes on two lines.

Comment by okonomiyaki3000 — April 7, 2010

I like it. Often when declaring variables like this, if a declaration spans multiple lines it can become confusing, or even look like someone forgot a ‘var’ before a declaration. With the comma at the beginning, it makes it obvious that it’s part of a set of declarations.

Comment by mjuhl — April 7, 2010

If you don’t want stupid errors, then write some automated tests. They’re much more useful than this comma-first style.

Comment by igstan — April 8, 2010

I’ve configured aptana to automatically syntax check my javascript code. Stray comma’s show up as red squigglies. Adapt the tool to the code, don’t adapt the code to the tool.

Comment by Joeri — April 8, 2010

I agree with the author, the code is only as ugly as you think it is.
I’ve been using this syntax for a while now and it doesn’t seem ugly anymore :-)
Besides it seems pretty useful, especially when it comes to commenting lines. With comma-first you can do this:
var a = “ape”
//,b = “bat”
,c = “cat”
whereas in the regular style you need to move some stuff around first or use /**/

I think you’re wrong, if the interpreter would inject semicolons, you’d get a bunch of errors and the code wouldn’t work.

Comment by Herhor — April 8, 2010

If have been programming “operator-first” for the last 20 years in almost every language I have used since, including C, C++, Java, Perl, JavaScript, Ruby.

I find operator-first easier to read and understand and absolutely not ugly.

Until this article I though I was alone.

Comment by jvincent — April 8, 2010

Interestingly, this problem doesn’t arrise at all in Lisp. When I code in Lisp for a while, I end up having this kind of problems in other languages way too often.

Comment by pupeno — April 8, 2010

I hate polish notation, it is just unnatural and makes the code harder to understand.
Besides, the reliability argument only makes sense if the code is correctly indented. Sadly colons errors are often introduced by sloppy editing and monkey-patching, therefor it’s pretty unlikely that this prefix notation would be respected by the person introducing the bug.

Comment by ywg — April 8, 2010

By the way, in javascript a line feed can be a semicolon. So the comma first style could be misinterpreted by the js engine!

Comment by fastner — April 8, 2010

@tonyl, I believe that the JS parser will add a semicolon if it’s missing from a line, and the check the next line. When it finds the comma, it will assume that the previous line was unfinished, go back, and remove the semicolon. So everything will work, but with worse parsing performance (and this of course is why you should minimize JS).

I believe Crockford talked about this, but I can’t find a good source right now. Again, correct me if I’m wrong.

Comment by joolss — April 8, 2010

Isn’t this just an issue for those who do not use jslint?

Comment by ruidlopes — April 8, 2010

I’ve been exposed to comma-first – and while “debug”-ability is certainly higher it is so on the price of readability. I would want scripts to have the latter.
Comma-first is fugly – especially when introduced in scripts that already use the (IMO) standard notation.
( Oh my! – The spam questions suddenly got much harder :P )

Comment by rasmusfl0e — April 8, 2010

I used to use operator/comma first programming style when writing PHP years ago. This was true even of the long SQL statements I would write, where each clause (starting with operator) was on its own line. But it’s helpful if you have an if-statement with 6 different statements separated by || or whatever. I did it because having a list of items with operators or commas in between, it’s easier to comment out any of the lines (except the first) of that list and have the list still be valid.
It makes commenting out the FIRST item more awkward, but it trades that for being able to comment the last item out easily, or add to the end of the list (with only changing one line, not two) as okonomyaki mentioned. So I think it’s a small slight net-gain in maintainability.
I think what I did in the case of the SQL was to actually have “TRUE” as the first line of the WHERE conditions list for instance, that way it wouldn’t matter if it was part of the SQL statement and I could comment out or add lines to the rest of the list to my heart’s content, but only needing to change one line at a time. Definitely made heavy code maintenance easier.
I’m not sure why I went away from that style, but I don’t do it any more now that I focus exclusively on JS coding. This makes me wonder if I should revisit the style.
On a side note, I do always put var statements with multiple declarations, with one declaration per line, for the same commenting out/adding ability, although it makes the adding to the end action more awkward as stated. It’s funny, but similar to what I used to do with the SQL statements, I now will pick one variable declaration to be the last one of my var statement list, and separate it by a newline or two at the end, and put the ; with it. That way I can add to the “end” of the list by just inserting items before the newlines break and pretend that the actual last item just isn’t even there. :)

Comment by getify — April 8, 2010

Another place (again in C or PHP style languages) I use the comma first style still is in sprintf() lists… because there’s a guaranteed first parameter to that function, with a variable number of additional parameters… so being able to list them out one at a time, and be able to comment them out easily or add to them, is a nice slight improvement. Seems like this would be true with any function call signature who is designed to take a variable number of arguments.

Comment by getify — April 8, 2010

This form moves the weirdness from the last line to the first line. When this form is used with the return statement, semicolon insertion will strike. Therefore, I recommend not using this form.

Comment by crock — April 8, 2010

I am OCD when it comes to syntax, so I think this would drive me crazy, although I wouldn’t fault someone for using it if they can avoid the problem crock and tonyl mentioned above.
But to suggest beautiful code doesn’t exist? I couldn’t disagree more!

Comment by RyanMorr — April 8, 2010

This is interesting. It reminds me of the fact that when I write sql I prefer to structure my where clauses like this:

where col1 = val1
and col2 = val2
and col3 = val3

instead of

where col1 = val1 and
col2 = val2 and
col3 = val3

That said, comma-first would take some getting used to.

Comment by hammond13 — April 8, 2010

I hope comma first doesn’t become popular…

Comment by WillPeavy — April 8, 2010

I’ve been programming for 25 years and just recently made the switch in my javascript programming. I found the switch easy and very helpful.

Comment by dejohns2 — April 8, 2010

My essential complaints about this style are the same as my complaints about any purely structural style guidelines for programming:

First, the style is no substitute for common sense. It is an easy rule to apply. Other rules like it are also easy to apply. Unfortunately, it is equally easy to simply not make the mistake in the first place. And even more unfortunately, my belief is that if you are applying stylistic rules and expecting them to save you then you’re more likely to miss problems when they style rules do *not* make them stand out.

Second, the style must be applied uniformly to be effective, and in a mixed codebase you can never ever ever expect such a style to be applied uniformly. Not only will people who are less experienced with the style just plain going to mess up at times, but there will be people who reject the style violently. Once your code is no longer uniformly using this style, you lose all of its benefits.

In short: The difference in the ease of spotting syntax mistakes between this style and the more traditional style is minor. Any gains are offset almost immediately as soon as your start collaborating with other developers, because they will fail to apply the style correctly or refuse to apply the style. In the end you gain almost no benefit at the expense of exasperating people who don’t like it.

For the record, I’m one of the kind of people who don’t like it. If I’m working with somebody and they inject a style like this into my codebase, I have to re-train them to stop using it, because it doesn’t match, and it doesn’t do them any good when 90% of the code isn’t like that.

If I’m working on somebody else’s codebase and they use this style I’ll of course keep to their style while in their code. But if there’s an alternative codebase available that does what I need and doesn’t use this sort of style, I’ll shift my work to that project at the first opportunity.

Comment by Hypatian — April 8, 2010


I’m not sure what you mean by “When this form is used with the return statement, semicolon insertion will strike.” I updated the gist with some examples of using this with the return statement. I do this regularly in my code, and there’s no problem.

Regarding “moving the weirdness”, the line that contains weirdness wasn’t really my point, though others have brought that up as a benefit. My point is that it moves the wierdness from the last *column* to the first *column*, which means that an incongruous line is completely out of joint, and easier for a human brain to detect.

Comment by IsaacSchlueter — April 8, 2010

Definitive proof that this method is junk.

Comment by rwaldron — April 8, 2010

@hammond13: I do that too, but end up doing the second if I end up in parenthesis:

FROM `xyz`
WHERE `x` = 1
AND `y` = 2
AND (`x` = 2 OR
`y` = 2)

Comment by ellisgl — April 8, 2010

@rwaldron I think you are confusing “definitive” with “religious”

Comment by IsaacSchlueter — April 8, 2010

We use 1-line CSS, where that attributes are alphabetical and spaces occur after the semi-colons.

.selector { ard:var; flu:bug; foo:bar; }

It makes any SVN conflicts very apparent.

@hammond13 – We do the same, but indent the ANDs and ORs.
FROM `xyz`
WHERE `x` = 1
AND `y` = 2
AND (`x` = 2
OR `y` = 2)

Comment by Benxamin — April 8, 2010

Is this where Ajaxian has come to? An article on the coding style?

Comment by ragjunk — April 8, 2010


I am a left-margin person and I use indentation and other devices to guide me through the structure. (I also like it when editors will notice and allow me to do collapsos and expandos, but that isn’t essential.)

For me, the right-margin stuff is an abberation having to do with parser oddities or long-forgotten practices (such as “{” at the right) that have become peculiary habits.

I use a common layout style for all of the languages I program, and the leading separator (“,”) will be a very useful way to confrim that what I see is what it is.

Since I am the only person who has review authority over my code, I am going to put this in at once. It works in more places than EcmaScript.

Comment by orcmid — April 8, 2010

“Create code that is stable”
– meaning each line should be able to move around (IF POSSIBLE) without breaking the intent of the code.

Abusing multiple assignments just to save from typing “var” fits into that category.

Comment by functionform — April 8, 2010

@functionform first of all “IF POSSIBLE” shoots a hole in your statement becuase there’s LOTS (in fact *most*) code that is in a specific place/line because it has to be there and only there to work. If you argue that the “intent” clause allows non-functioning code, perhaps you could say that… but me taking one statement of my source code and being able to move it up several lines and still have my code look stable is kind of a spurious requirement, since the code would in fact not BE functionally stable.
The fact is, there’s lots of code (*most* in fact) that gets written in such a way that the line some code appears on is the only line it can appear on both from an “intent” standpoint and from an functional standpoint.
I think it’s silly to argue that it’s lazy or “unstable” to save lots of repetitive “var” statements (and significant file size sometimes!) just because a single line in such a var statement is not standalone independent to be able to move around. This is a common practice in JS and leads to smaller file sizes and faster loading code.
It’s a case where pragmatism needs to win out over philosophical opinion.

Comment by getify — April 8, 2010

The main arguments against this seem to be aesthetic. Sure it’s ‘ugly’ if you aren’t used to looking at it. It doesn’t take long to get used to it though and then it’s not ugly at all. Like several others have pointed out, it’s very very useful when writing long SQL queries (for some of us, js is not the only language we use).

The semicolon issues in js may be valid points (or not?) but only if you’re not compressing your code and why would you not do that?

Comment by okonomiyaki3000 — April 8, 2010

I first saw this style about two years ago and decided to give it a try since I already like to use operators at the beginning of continuation lines in other languages. The other two developers in my company also started formatting their code in this manner after seeing me use it. We all find that it makes code more readable and that it feels pretty natural after using it for only a short time.

Comment by pjs — April 12, 2010

Catching stupid typos, finding incorrect logic, and writing better code all have the same solution: unit tests. You won’t like writing tests at first, and then you won’t know how you wrote code without them!

Comment by nuttzy — April 13, 2010

Leave a comment

You must be logged in to post a comment.