Commas Before

Avatar of Chris Coyier
Chris Coyier on

Marc Grabanski brought up and interesting idea on Twitter yesterday.

Commas before or after the line on json objects and multi var definitions?

Here are examples of object literals:

// commas before
var vampyre = {
    teeth: 'sharp'
  , blood: 'stale'
  , age: 320
}

// commas after
var vampyre = {
    teeth: 'sharp',
    blood: 'stale',
    age: 320
}

You probably see commas after structure the vast majority of the time. It “looks right.” But the commas before makes these bits of code easier to work with.

Let’s say you want to comment out one line. With the commas before technique, you just comment out the line like you would any other line of code in JavaScript by prefacing it with “//”. With the commas after structure, you have to be more careful about that. If you were to comment out the last declaration (age), the last declaration would end with a comma and throw an error. So then you are left either manually removing that comma or also commenting it out.

It’s technically a horse apiece, since commenting out from the middle of a block of declarations is the same either way. Commas before make it easier commenting out the last declaration and commas after make it easier to comment out the first.

Works the same way when declaring mutliple variables in one statement:

// commas before
var foo = 'bar'
  , boo = 'baz'
  , doo = 'dad'
  ;

// commas after
var foo = 'bar',
    boo = 'baz',
    doo = 'dad';

Notice the semicolon being first as well (via Scott González). This helps keep the ease of commenting alive (the whole point), in that you won’t comment out the semicolon when commenting out the last line.

It’s a really small thing, and it looks weird, but I’m a fan of the commas before idea. I think it comes down to the fact that when adding new declarations, I like to do it at the bottom and in such a way that, while testing, it’s quicker and easier to comment out.