Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trailing comma after last line in object

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.

like image 408
Eliran Zeitouni Avatar asked Apr 22 '20 16:04

Eliran Zeitouni


People also ask

Can trailing commas be used in objects and arrays?

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.

What is a trailing comma?

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.

How do I remove a trailing comma from a string?

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.

What is a leading comma?

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.


2 Answers

You can update .prettierrc.json and set option trailingComma to none like:

{   "trailingComma" : "none",   ... } 
like image 156
Zuckerberg Avatar answered Oct 11 '22 11:10

Zuckerberg


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.

like image 36
gschenk Avatar answered Oct 11 '22 12:10

gschenk