ECMAScript – Trailing Commas
What is trailing comma & why?
Trailing commas is also called as final commas.
Arrays, Object literals, function parameters allow trailing commas. However, JSON doesn’t allow trailing commas.
Trailing commas in Array literals
If more than one trailing comma is used, an elision (or hole) is produced. An array with holes is called sparse (a dense array has no holes). When iterating arrays for example with Array.prototype.forEach() or Array.prototype.map(), array holes are skipped.
However, the final comma in the array is ignored.
Trailing comma is supported in Object literals from the ECMAScript 5 edition.
Trailing commas in functions
ECMAScript 2017 allows trailing commas in function parameter lists.
Trailing commas allowed function definition and function calls. Trailing commas don’t affect the length property of function declarations or their arguments object.
Function parameters with commas only are invalid which will throw SyntaxError.
What about Internet Explorer Support?
The babel will convert our scripts with trailing commas to support the IE.
Example: It will remove the commas while building the package.
Left side: Our ECMAScript code
Right side: Equivalent Code generated by babel
makes version-control diffs cleaner and editing code might be less troublesome
Let’s talk about the main advantage, the Version control support.
Check out the below sample, I’m trying to add an entry to list to two arrays.
One has trailing commas and other not. When we are adding an entry to an array which has trailing comma, the GIT diff looks clean. That’s the main advantage of this whole concept.
When we are having a trailing comma, it only shows the addition of entry.
And again, its based every individual to decide whether they want to use this concept or not.