In most Node.js libraries people take special care removing trailing commas after the last key-property pair of objects:
var test = {
key1: 123,
key2: 456,
key3: 789
};
This produces some troubles while editing the code, e.g. to swap last two key-value pairs one has also to add one comma and to remove one. Some people move commas to the next line, which solves the issue with the last element but also makes the code a bit harder to read (IMHO):
var test = {
key1: 123
, key2: 456
, key3: 789
};
On the other hand as far as I know the trailing commas in JavaScript produce troubles only in some IE browsers. So I'm wondering are there any technical reasons not to write hashes with trailing commas in Node.js? (Like the following:)
var test = {
key1: 123,
key2: 456,
key3: 789,
};
Trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to JavaScript code. If you want to add a new property, you can add a new line without modifying the previously last line if that line already uses a trailing comma.
In general, you should make use of trailing commas when you frequently copy/paste properties or add new items to the end of a list. You can also take advantage of them to produce cleaner diff outputs.
No. The JSON spec, as maintained at http://json.org, does not allow trailing commas. From what I've seen, some parsers may silently allow them when reading a JSON string, while others will throw errors.
In JavaScript, there's a standard comma style for adding commas to our code. For multiple variable variables and constant declarations, we have a line break after a comma. This also applies if we have long expressions in arrays or having a list of properties inside an object.
It probably won't improve your runtime or anything like this, but you have a vantage using the trailing comma related to the version control.
If you do not use it, git will detected that one line was modified and another one was added. But if you use it, git will detected that only one line was added:
With using trailing comma:
Without using trailing comma:
No, there is no technical reason to do that.
However, I never put trailing comas just because I think it makes for cleaner code. Probably some also have the habit coming from web development where, like you mentioned, you need to be careful about those because of IE.
Edit: This answer made sense back in 2012, but today, with major browser support and tools like Babel for older browsers, I think trailing commas should be the default for everyone. The benefits are that it makes adding a new line easier, and the relevant Git diff is cleaner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With