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

javascript trailing comma

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

one,two, three

trailing commas in javascript allows to add the comma after the last element. Javascript compiler ignore by trailing commas

one,two, three,

Advantages with trailing commas

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

There are number of objects types uses trailing comments syntax change

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

Array Data in ES3

ES3 introduced to ignore trailing commas in Array data

let array=[1,
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 ignore by compiler. This was supported since ES5.

const obj = {
  id: 's1',
  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 stills prints actual data length.

ES8 trailing commas in Functions

Functions contains Definition and caller. ES8 allows to support trailing commas in function parameters and function calls.

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

function getMessage(str,str2,){
  console.log(str+'='+str2) ;

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

function getMessage(,){
  console.log(str+'='+str2) ;

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