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 adding the comma after the last element. Javascript compiler ignore 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
final comma
ortrailing comma
. - git comparison makes cleaner with final commas
There are many objects types that use 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 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 are valid.
function getMessage(str,str2,){
console.log(str+'='+str2) ;
}
getMessage("hello","frank")
getMessage("hello","Tom",)
if there are not arguments in function, trailing comma is included, 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