Trailing comma after last line in object

38,278

Solution 1

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

{
  "trailingComma" : "none",
  ...
}

Solution 2

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.

Solution 3

Trailing commas are a standard already because they result in a cleaner commit history. If you have to add a property down the road, git will show a single line changed instead of a new line AND the new comma on the previous line.

Solution 4

To modify the setting in VSCode:

  1. Go to FILE -> PREFERENCES -> SETTINGS. (VS Code Menus)
  2. Settings window should open. Above (Top) there is a search. Type "Prettier"
  3. You should see the available Prettier settings. You can modify them

Now change trailingComma to none

Solution 5

Trailing commas are modern JS, but if you really don't like them they can be disabled.

Share:
38,278
SiiilverSurfer
Author by

SiiilverSurfer

Updated on March 02, 2021

Comments

  • SiiilverSurfer
    SiiilverSurfer about 3 years

    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.

  • Yevhenii Herasymchuk
    Yevhenii Herasymchuk over 3 years
    could you add any source, any article about "trailing comma - modern js " ?
  • gimboland
    gimboland almost 3 years
    Solution: apply the change to your entire codebase, commit that, and add the commit to .git-blame-ignore-revs so it doesn't show up in blame — see e.g. akrabat.com/ignoring-revisions-with-git-blame
  • Mārtiņš Briedis
    Mārtiņš Briedis about 2 years
    @YevheniiHerasymchuk It's not only JS. It's, for example, PHP too. Trailing commas avoid conflicts when two people add items to an array/object and then want to merge with git. With a trailing comma, instead of a modified line + inserted line, you only get an inserted line which won't produce any conflicts.