Hacker News new | past | comments | ask | show | jobs | submit login
Regarding JavaScript trailing commas (dontkry.com)
69 points by erikw on April 9, 2016 | hide | past | favorite | 47 comments



I'm a Python programmer. In Python, trailing comma are idiomatic, so I welcome this.

Perhaps I'm just a lazy bastard, but it makes cut & paste a lot easier.


Ditto, from the Perl side of things. I'm a JS coder for the last few years, and I find I really hate a lot of the style conventions - they seem much more oriented towards "because I said so" than "because it's actually better".


Many common JS conventions are because they were critically important at a.) the time the lead programmer learned Javascript or b.) the time the codebase was originally written.

Trailing commas are certainly in that category. When I started getting into JS seriously in 2007, this wasn't a nitpick: your code would be outright broken in IE6 if you had a trailing comma, and would fail with a syntax error. This was a leading cause of IE bugs, since developers often developed in Chrome or Firefox (which handled them fine) and it was ridiculously difficult to trace it down.

Ditto a lot of other conventions. It was common to use innerHTML instead of DOM manipulation because IE was ridiculously slow at DOM manipulation (React just fixed this in their codebase this week). It was common practice to wrap every file in a closure because all your variables would pollute the global scope - now we have CommonJS modules and bundlers to handle this. It was common to avoid closures in favor of prototypes & _ naming conventions because Firebug & Chrome Devtools couldn't inspect variables in closures.

All of these are terribly obsolete now, and there's no reason to adopt them on a new green-field project. But the point of coding conventions is uniformity with existing code, so if you're inheriting a codebase that was written when these were actually important, it's often good to conform just for consistency's sake.


Same with PHP.

I'd love to start using trailing commas in JS, but I've definitely had syntax error problems and unparsable JSON from them existing in recent memory.


This might be happening if you haven't updated your JS tools (although JSON is a different beast altogether). Look into fixing it, you'll be having way more fun once you've done so.


I would argue that the trailing comma diff issue is an artefact of the fact that diff works at the text level, not at the syntax level (I can only hope this might be a thing someday)


Sounds like an absolute nightmare of a problem to solve. And a maintenance nightmare.

Languages change over time.


I would imagine any version control system attempting to solve this problem would focus very closely on one particular language or development system. Any pragmatic solution would also have to be a highly opinionated one.

For a related idea, see Facebook's Haskell system, in which only type-safe code is allowed to be checked into the respository:

https://code.facebook.com/posts/745068642270222/fighting-spa...


In some versions of IE, trailing commas add an 'undefined' element to the end of an array.

Not sure if there are any other interpreter inconsistencies.


Oh, I see: the reasons are syntax error, diff, consistency,.


The only time you should avoid trailing commas is if your javascript needs to run on older browsers.

If you use babel, you can write your source with trailing commas, then let the build step remove them for older browsers.


Right. Anything but losing the damn commas.

   nineties {
     dude: true
     awesome: true
     rad: true
   }


Well, that opens up a whole new can of syntax worms...

But yeah, all of this stuff just makes me more convinced that Lisp syntax is the best ever.


Lisp uses comas in macro evaluation, but not lists and dictionaries. Then you have reader macros. Lisp syntax can be arbitrarily complex.


It's not that the symbol comma is bad. Lisp uses it as a prefix to unquote a form, which is totally different from the use as a separator.


The commas do something in backquote syntax! They are operators, effectively.

In the Scheme backquote (dubbed quasiquote), the spec says that the read syntax ,X produces (unquote X). You can omit the comma, and then you just have X.

This is totally different from a comma which just punctuates syntax.


macro and comma is fully unrelated. The comma in backquote expressions is not even limited to lists. Commas are used in backquote forms to force evaluation.

For example one can write a vector of three elements, where the second element is computed:

    `#(1 ,(first *features*) b)
Backquote list forms happen to be used in some macros as a kind of template forms. Macros can be defined without them and backquote forms are also used elsewhere in Lisp.


They are not "fully unrelated". The backquote syntax for constructing lists was primarily designed for macro programming. See the paper Evolution of Lisp by Guy Steele and Peter Gabriel:

"Macros took a major step forward with Lisp-Machine Lisp, which consolidated the various macro-defining techniques into two standardized features that were adopted throughout the MacLisp community and eventually into Common Lisp. The macro defining operator DEFMACRO provided list-structure destructuring to arbitrary depth; the backquote feature provided a convenient and concise pseudo-quoting facility. [ ... ] Backquote and DEFMACRO made a big difference. This leap in expressive power, made available in a standard form, began a new surge of language extension [...]" [3.3]



In my opinion it is just a matter of personal taste, if I move some code without trailing commas I make sure that the commas are in the right place. This actually can be seen as an advantage given that blind copy and paste is the source of all evils, so a syntax error will force you to reconsider what you have just done blindly. All in all I don't see a problem in using either styles, it's only one character difference at the end.


For compiled languages like Rust, you might be correct, though even there I use trailing commas, specifically for the reason mentioned. It reduces bugs when you add or swap around array elements.

In a compiled language you catch this because it's a syntax error. In JavaScript, it might be missed through every code review (because it's subtle) and and then break on release to you production system.

So it's not just style, it can help reduce bugs.


I don't actually know the history of JavaScript style, but I feel like this assertion is likely trivializing something more complex:

>The reason you were once told trailing commas are bad is because they are invalid in EcmaScript 3.

I can imagine plenty of reasons people would have for avoiding trailing commas even after they became valid syntax.

The whole "consistency" section also feels like unnecessary snark.


> I can imagine plenty of reasons people would have for avoiding trailing commas even after they became valid syntax.

Could you list a few?


I've actually come to like a weird style popular in the Haskell world, leading commas:

    { one   = 1
    , two   = 2
    , three = 3
    }
It's weird, but it's actually pretty convenient. I think it has all the same properties the article argues for, but I don't want to figure it out for sure at the moment.


In my eyes this is really awful. Furthermore, if you move the first entry in the last place as is you get a syntax error. So it has all the disadvantages of the code without trailing commas, plus it makes your eyes bleed if you are used to read pretty much anything apart Haskell code.


I like that Data.Sequence bypasses this whole issue by just not doing anything special:

    empty
      |> ("one"  , 1)
      |> ("two"  , 2)
      |> ("three", 3)
Edit: It's interesting that, when we have things that are supposed to commute, we use infix operators that create a layout that makes it difficult to reorder them.


I've always found this style a lot better and can't figure out why people don't use it.

Adding items to the end of a list, tuples to a dictionary, arguments to a function etc... is more common then adding them to the start.


No way. What you if had to cut and paste the first item?


Then it's extremely obvious that it needs fixing, and your cursor is usually right there to make the change.

It is marginally more difficult than leaving in trailing commas, but way better than adding missing unaligned commas at EOL.


I think the argument would be that this is rarer


For the love of god though don't suddenly start using this style in a project that doesn't (I've had to deal with it)


It's worth mentioning that Elm uses this style: http://elm-lang.org/docs/style-guide#types

I was initially surprised by this but now knowing that the creator comes from a Haskell background, it makes sense that he would prefer it.


I tend to remove them because trailing commas break JSON. The similarities between JS and JSON are small enough for me to get confused over it and I'd rather remove the cause of potential errors there altogether.


Trailing commas were tough to get used to because my primary communication language is English,

After a while I got used to them and I like the copy-paste-ability the enable... I'm also hoping they put an end to leading-comma style,


There is so much in programming that isn't necessarily directly in line with English, why are trailing commas any different?


This was just my opinion, and it was not based on logic: I battled through and now I'm a happy trailing comma-er. But if I think about your question, I'd say the answer was because commas are the only part of coding that has a strong resemblance to written english in that you commonly use them to separate items a list.


Yes I like them in PHP too


Controversies like the "trailing comma" strike me as evidence that JavaScript has superfluous syntax. The reason it even uses commas the way it does is that it started life as a lisp with (manager-mandated) Java-like syntax.

I happen to agree with the position that syntax that can be made implicit should be. CoffeeScript has done a good job of this. LiveScript has done an even better one. What are the arguments against using a syntactically cleaner language that compiles down to the exact same features?


> Is there a good reason not to use a syntactically cleaner language ...

I find Coffeescript hard to read. Especially when dealing with nested callbacks (e.x.: when you have to nest, such as with Jasmine `describe` and `it` blocks for testing).

Here's an interesting thread on the "cons" of using Coffeescript: https://news.ycombinator.com/item?id=6527316


Fair enough. Maybe CoffeeScript specifically isn't the answer. But the general idea of compiling neater languages into JavaScript strikes me as a better long-term solution than settling for its current syntactical warts, which are entirely historical accidents.

I do like ES6!


I think ES6 is the solution. Evolve JS and remove the "warts" instead of introducing new variants.

I'm a big JS fan. I can't stand Coffeescript - it doesn't seem to add anything except changing the syntax to make it easier for Rubyists to understand. Which is fine, I guess, but feels like a personal preference. More like a text editor setting than something anyone should publish their code in.

Same for Typescript, to a certain extent, though I understand the heartfelt desire to have the compiler pick up some of the more common errors.

We run the risk of fragmenting the community by promoting CS and TS - better to evolve JS itself, which is what is happening and it's great.

TL;DR: kill Coffeescript and Typescript, evolve Javascript for the win!


I agree. Language features such as async/await (ES7) are exciting.


I am excited by async/await but it makes code non-trivially harder to debug. The tools are far from there


> CoffeeScript has done a good job of this

And that language shouldn't be used by beginners in 2016 due to its uncertain fate in the long run as its creator kind of abandoned the project. Furhtermore ES2015 adds many CS features to the language.

Don't know about LiveScript, but frankly that whole transpilation thing is a mess. People don't use Transpilers for Python or Ruby. They work with the language quirks.


Some of the features of ES6 are pretty neat. Some of them are just crap piled on crap, which bloat out the language for marginal benefits at best.

Unfortunately, many of the ES6 features inspired by CoffeeScript features are completely unoptimized and an order of magnitude slower in cutting-edge browsers than the CoffeeScript versions. Even more unfortunately, they don’t work at all in lots of browser versions people are still using today. Which means that they can’t really be adopted by most projects yet.

Finally, even if ES6 were implemented perfectly everywhere, it’s still much less pleasant (from a syntax clarity perspective) to read and write ES6 code than CoffeeScript code, at least for me.

At the point when the vast majority of browsers support ES6 features, it will perhaps be reasonable to change CoffeeScript to use them in its generated output. In the mean time, CS is fantastic as-is, and its generated code works efficiently in every browser.

But hey, use whatever language you like (ClojureScript, Elm, Dart, Haxe, ES6, whatever..). It’s your code, so the only people who should care are you and your close collaborators.


So use Babel, as long as you're using a compiler anyway?


Not my personal cup of tea (I don’t particularly like the ES6 syntax, and as I mentioned many of the nicer features are horribly inefficient in current browsers), but use whatever you like!




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: