For more tips like this, sign up to the weekly newsletter!

Trailing comma

With ES8, trailing commas are allowed pretty much everywhere. It seems like a little addition, but there are some hard-to-notice consequences. And while most new language features are welcomed, this one is strangely controversial.

What is a trailing comma?

It is when you add a comma after the last element of a list. For example, this is a valid array declaration:

[
  1,
  2,
  3,
]

You can use them in array, object, and function declarations, and function calls.

Advantages

  1. Easy reordering

No additional work is required if you move the last line around the list.

  1. Easier code generation

No extra logic is needed when generating lists of elements.

  1. Easier diff

Without a trailing comma, adding a new element changes two lines. With a trailing comma, only one line is changed.

Drawbacks

  1. JSON disallows it

While Javascript supports trailing commas, JSON does not. This might cause unexpected errors, and it is yet another difference between Javascript's Objects and the Javascript Object Notation (aka. JSON).

  1. It seems wrong

Developers learn the hard way to take extra care to write everything correctly. A missing = from an == might mean an extra hour spent on debugging, and that evolves the strange lingering feeling that something is missing from the Coffee & More logo. A dangling comma evokes the same feeling, and veteran coders can't help themselves but remove it. Old habits die hard.

Try it
References
Learn more: