Table of contents
Please support this book: buy it (PDF, EPUB, MOBI) or donate
(Ad, please don’t block.)

10. Trailing commas in function parameter lists and calls

The ECMAScript 2017 feature “Trailing commas in function parameter lists and calls” was proposed by Jeff Morrison.

10.1 Overview

Trailing commas in parameter definitions are now legal:

function foo(
    param1,
    param2,
) {}

Similarly, trailing commas in function calls are now also legal:

foo(
    'abc',
    'def',
);

10.2 Trailing commas in object literals and Array literals

Trailing commas are ignored in object literals:

let obj = {
    first: 'Jane',
    last: 'Doe',
};

And they are also ignored in Array literals:

let arr = [
    'red',
    'green',
    'blue',
];
console.log(arr.length); // 3

Why is that useful? There are two benefits.

First, rearranging items is simpler, because you don’t have to add and remove commas if the last item changes its position.

Second, it helps version control systems with tracking what actually changed. For example, going from:

[
    'foo'
]

to:

[
    'foo',
    'bar'
]

leads to both the line with 'foo' and the line with 'bar' being marked as changed, even though the only real change is the latter line being added.

10.3 Feature: allow trailing commas in parameter definitions and function calls

Given the benefits of optional and ignored trailing commas, the feature brings them to parameter definitions and function calls.

For example, the following function declaration causes a SyntaxError in ECMAScript 6, but is now legal:

function foo(
    param1,
    param2,
) {}

Similarly, this invocation of foo() is now syntactically legal:

foo(
    'abc',
    'def',
);