I'm using Prettier in VS Code. I noticed that when using format on save, Prettier adds trailing commas on the last line of an object every time.
For example, let's say I had a JS object like this:
obj = { hello: 'hello', world: 'world' }
Prettier turns it into this:
obj = { hello: 'hello', world: 'world', }
Notice the extra comma after
'world'
Didn't find in the settings an option to fix this.
JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals, and more recently, to function parameters and to named imports and named exports. JSON, however, disallows trailing commas.
A trailing comma, also known as a dangling or terminal comma, is a comma symbol that is typed after the last item of a list of elements. Since the introduction of the JavaScript language, trailing commas have been legal in array literals. Later, object literals joined arrays.
To remove the leading and trailing comma from a string, call the replace() method with the following regular expression as the first parameter - /(^,)|(,$)/g and an empty string as the second.
Leading comma advocates typically argue that leading commas are better because you can easily comment out lines in a query without having to edit other lines. With trailing commas, that edit is necessary to prevent errors and, they say, easy to forget.
You can update .prettierrc.json
and set option trailingComma
to none
like:
{ "trailingComma" : "none", ... }
Trailing commas are a code-style convention that was introduced to avoid spurious differences in version controls (ie Git).
Imagine you have version controlled code and you have to change it. When you add a new line to your object without the trailing comma, you will have to change the original last line by adding a comma. In version control this then shows up as two changed lines. The code reviewer or a future dev have to check if you effectively changed the last line, or only added the comma.
Zuckerberg's answer shows you how to change it. However, it is better to change your style, than change prettier's style.
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