Please support this book: buy it (PDF, EPUB, MOBI) or donate

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:

  1. function foo(
  2. param1,
  3. param2,
  4. ) {}

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

  1. foo(
  2. 'abc',
  3. 'def',
  4. );

10.2 Trailing commas in object literals and Array literals

Trailing commas are ignored in object literals:

  1. let obj = {
  2. first: 'Jane',
  3. last: 'Doe',
  4. };

And they are also ignored in Array literals:

  1. let arr = [
  2. 'red',
  3. 'green',
  4. 'blue',
  5. ];
  6. 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:

  1. [
  2. 'foo'
  3. ]

to:

  1. [
  2. 'foo',
  3. 'bar'
  4. ]

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:

  1. function foo(
  2. param1,
  3. param2,
  4. ) {}

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

  1. foo(
  2. 'abc',
  3. 'def',
  4. );