var object = {
foo: "bar",
baz: "qwerty",
age: 42, <<--
};
var arr = [
1,
2,
3, <<--
];
One major benefit of trailing commas is that they play well with version control.
E.g. let's say you have the following array:
const myArray = [
1,
2,
];
Later, you like to add an additional element:
const myArray = [
1,
2,
3,
];
Then, the diff file looks as follows:
const myArray = [
1,
2,
+ 3,
];
And not:
const myArray = [
1,
- 2
+ 2,
+ 3
];
Which IMHO is much less descriptive.
Depending on the language, that trailing comma can kick you in the nuts... since it can create an extra empty array or object element. That's a waste of memory, and can result in performance issues since you're allocating more RAM... much less what about telling how many ACTUAL elements there are?
In other languages it won't even make it past the compiler or execute stage...
So why the *** would you be doing that in the first place exactly?!? "oh noez, eyes bee two stupids two addz uh comas laters?"
I use it often in Python, but only if the list is spread over multiple lines. This makes it really easy to reorder the list by exchanging the lines, as I don't have to take care of that comma.
Also in Python you can declare a tuple (an immutable list type) with one element using it: my_tuple = ('the element',)
Thus I consider it a necessary evil sometimes, but definitely not always.
They're part of the standard and don't cause any issues other than minor annoyance to that OCD demon in the back of our human minds when reading through code that contains them, at least as far as I'm aware.
Leaving them in makes it easier to adjust array and object literals if you're copy / pasting things or using keyboard shortcuts to delete lines or enter newlines (vim's dd and o for instance).
Only thing to remember is that they're invalid in JSON.
I like the trailing comma because it makes it simpler to add elements later. But I agree that it's poor form to keep them in. An alternative would be to put the comma at the beginning of the line, so copy/paste elements is simpler. You don't forget the comma.
var object = {
foo: "bar"
, baz: "qwerty"
, age: 42
};
Been using them in PHP forever and it makes dealing with Arrays so much easier.
Started in JS now we only use build tools and again, it makes life so much easier. In fact on one project I have my linter to complain if I don't have them!
Don't do it in JSON if you're deserializing with GSON.
Stian Bakken
Full stack development with NodeJS/Aurelia
I've heard main reason why people like trailing commas, is because if someone adds another property to an object, or another item to an array, they do not have to "take ownership" of the previous line in the git commit.