Search code examples
javascripthtmlvisual-studio-codechart.jsprettier

Why prettier put a comma ',' at the last element of the object


In Visual studio code, When I am using chart.js in my app, prettier always put a comma at the end of the last data of the object 'label'. I think, it's create a bug which unable to show my chart on my browser. it show blank. Code is given bellow.

let massPopChart2 = new Chart(myChart2, {
  type: "bar", // bar, horizontalBar, pie, line, doughnut, radar, polarArea
  data: {
    labels: [
      "1st Day",
      "2nd Day",
      "3rd Day",
      "4th Day",
      "5th Day",
      "6th Day",
      "7th Day",
    ],
  },
});
can anyone help me figure out why this happening?


Solution

  • JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ECMAScript 5) and most recently (ECMAScript 2017) to function parameters.

    This is a relatively new change in syntax, but the basic idea is that by putting a comma on each line allows for:

    1. Easier to add an item or re-order items. Before you always had to check the trailing comma and make sure it was present or removed depending on location.
    2. Removes the need to have one line item be special because it lacks the ,.
    3. Allows for cleaner Git diffs.

    You can read up on the full documentation if you like - it goes into further detail: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas


    As far as the issue with your chart not displaying, unless you are using a very old browser, a trailing comma should not cause an error/information to not display.