This post talks about the object.values() method and its examples.

javascript trailing comma

In javascript, if there are multiple elements considered in code, each element is separated by a comma ,.

one, two, three

trailing commas in javascript allows adding the comma after the last element. Javascript compiler ignores by trailing commas

one, two, three,

Advantages with trailing commas

  • It enables the addition of the elements easily as the last line can be copied and added to a new line, modification is not required to remove the final comma or trailing comma.
  • git comparison makes cleaner with final commas

Many object types use trailing comments syntax change.

  • Array data - ES3 introduced to support it
  • Object literals - ES5 introduced to support it
  • JSON is not allowed - Not supported in any javascript version
  • Function definition - ES8 was introduced to support it
  • Function calls - ES8 was introduced to support it

Array Data in ES3

ES3 was introduced to ignore trailing commas in Array data

let array=[1,
2,
3,
]
console.log(array.length); //3
console.log(array); //[ 1, 2, 3 ]

And the output still prints the actual data, not the comma itself.

Object literal items in ES5

trailing commas are allowed in object properties as below. These will be ignored by the compiler. This was supported since ES5.

const obj = {
  id: 's1',
  name:'tom',
  sal: 1000,
};

console.log(obj); //{ id: 's1', name: 'tom', sal: 1000 }

And the output still prints the actual data, not the comma itself. Length properties still print actual data length.

ES8 trailing commas in Functions

Functions contain Definition and caller. ES8 allows supporting trailing commas in function parameters and function calls.

Function definition contains trailing commas to parameters and calling the function with trail commas in arguments is valid.

function getMessage(str,str2,){
  console.log(str+'='+str2) ;
}
getMessage("hello","frank")
getMessage("hello","Tom",)

if there are no arguments in the function, a trailing comma is included, the compiler throws SyntaxError: Unexpected token,

function getMessage(,){
  console.log(str+'='+str2) ;
}
getMessage("hello","frank")
getMessage("hello","Tom",)

And the output error is

function getMessage(,){                    ^
SyntaxError: Unexpected token ,

Support This will support in latest browsers To support in older browsers, enable the following plugins in your project.

  • polyfill
  • babel plugin