Revision: Upon pondering the above question, I delved into a long-standing irritation that led me to justify the use of leading commas: they make it easier to identify missing commas. This can prevent potential bugs where the compiler doesn't flag an error but automatically adds a semicolon, altering the code significantly:
var a = foo(),
b = bar() // Whoops...
c = baz(); // Ouch!
The third line no longer creates a new variable within the current scope; instead, it assigns to an existing variable in an outer scope or initializes a new global variable.
While this reasoning applies to programming languages, it doesn't fully explain why leading commas are also used in JSON formats. It could simply be a carryover convention without solid justification.
Personally, I prefer separate declarations as they simplify and ensure safer code practices.
I'll preserve my viewpoint here for future reference.
I've noticed this trend across various libraries— almost every other one follows this pattern. But frankly, I find it puzzling.
Trailing commas complicate commenting out the last line of a block...
var //a = foo(), easy
b = bar(),
c = baz();
var a = foo(),
b = bar()/*, awkward
c = baz()*/;
...while leading commas create difficulties for both the first and last lines...
var /*a = foo() awkward
, */b = bar()
, c = baz();
var a = foo()
, b = bar()/* awkward
, c = baz()*/;
Is this progress?
(One could argue about optional semicolons, but that only achieves parity by sacrificing best practices.)
Furthermore, leading commas are also prevalent in JSON formatting. Take, for instance, this package.json file generated by Express:
{
"name": "application-name"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"express": "2.5.10"
, "jade" : ">= 0.0.1"
}
}
This can be frustrating since most editors don't handle indenting sibling lines differently from each other. Notice how the indentation differs between the first line and subsequent lines in a group.
Overall, using leading commas seems like a meaningless practice that introduces issues without offering any significant benefits. The argument that they align with each other is not very convincing.
Fortunately, CoffeeScript's rise in popularity renders this debate irrelevant (it even surpasses JSON for configuration purposes).
Revision: I should clarify that I do not endorse trailing commas in the scenario mentioned above. Personally, I believe declaring individual variables makes more sense. It's cleaner, consistent, and allows for easy commenting out of specific items.
var a = foo();
var b = bar();
var c = baz();