Skip to content

Trailing commas: cleaner diffs in lists (ES5–ES2017)

  • Every place JavaScript accepts a trailing comma, and the edition that added it.
  • Why trailing commas give smaller diffs and fewer merge conflicts.
  • Where a trailing comma is a syntax error (rest elements, lone commas, JSON) or changes meaning (array holes, regex quantifiers).
  • How formatters apply the style for you.

TL;DR: a trailing comma (also called a final comma) after the last item of a comma-separated list is optional and changes nothing at run time. Arrays always allowed it, object literals since ES5, destructuring and named imports/exports since ES2015, and function parameter lists and call arguments since ECMAScript 2017. JSON still forbids it.

Without a trailing comma, appending to a multi-line list also edits the line above it to add a comma. The diff shows two changed lines, git blame credits the wrong commit, and two branches that each append an item conflict.

const statuses = [
'pending',
'paid'
'paid',
'shipped'
];

With a trailing comma already in place, the same change is one added line:

const statuses = [
'pending',
'paid',
'shipped',
];

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The output shown under each sample was produced with Node.js 22.23.

// Trailing commas are allowed in every multi-line list below.
function createShipment(
orderId,
carrier,
options = {},
) {
return { orderId, carrier, ...options };
}
const shipment = createShipment(
'ord-1042',
'ExampleExpress',
{ insured: true },
);
const statuses = [
'pending',
'paid',
'shipped',
];
const { orderId, carrier, } = shipment;
const [first, second,] = statuses;
console.log(shipment, statuses.length, orderId, carrier, first, second);
console.log(createShipment.length); // trailing comma does not change Function.length
console.log(((a, b,) => a + b).length);

Output:

{ orderId: 'ord-1042', carrier: 'ExampleExpress', insured: true } 3 ord-1042 ExampleExpress pending paid
2
2

createShipment.length is 2 because length counts the parameters before the first default value; the trailing comma has no effect on it, or on arguments.length.

List Trailing comma allowed since
Array literal [1, 2,] ES1 (always)
Object literal { a: 1, } ES5
Array and object destructuring const { a, } = o ES2015
Named imports and exports import { a, } from './m.mjs' ES2015
Function, method and arrow parameters (a, b,) => {} ES2017
Call arguments f(a, b,), new C(a,) ES2017
Dynamic import import('./m.mjs',) ES2025, together with the import attributes options argument

Imports and exports in an OrdersPortal module, including a dynamic import with a trailing comma:

orders-lib.mjs
const ORDER_STATUSES = ['pending', 'paid', 'shipped'];
function formatOrderId(id) { return `#${id}`; }
export {
ORDER_STATUSES,
formatOrderId,
};
main.mjs
import {
ORDER_STATUSES,
formatOrderId,
} from './orders-lib.mjs';
const lib = await import(
'./orders-lib.mjs',
);
console.log(formatOrderId('ord-1042'), ORDER_STATUSES.length, lib.formatOrderId === formatOrderId);

Output of node main.mjs:

#ord-1042 3 true

Where a trailing comma is an error or changes meaning

Section titled “Where a trailing comma is an error or changes meaning”
const check = (label, source) => {
try {
new Function(source);
console.log(`ok ${label}`);
} catch (error) {
console.log(`SyntaxError ${label}: ${error.message}`);
}
};
check('param list with rest', 'function f(...items,) {}');
check('array rest element', 'const [head, ...rest,] = [1, 2, 3];');
check('object rest property', 'const { id, ...rest, } = {};');
check('lone comma in params', 'function f(,) {}');
check('lone comma in call', 'f(,)');
check('parenthesized expression', 'return (1, 2,);');
check('arrow params', 'return (a, b,) => a + b;');
// Two trailing commas in an array make a hole.
const sparse = [1, 2, 3, , ,];
console.log(sparse.length, 3 in sparse, sparse);
// JSON never allows trailing commas.
try {
JSON.parse('{ "orderId": "ord-1042", }');
} catch (error) {
console.log(`${error.constructor.name}: ${error.message}`);
}
// In a regex quantifier the comma changes the meaning.
console.log(/^\d{3}$/.test('12345'), /^\d{3,}$/.test('12345'));

Output (V8’s messages; other engines word them differently):

SyntaxError param list with rest: Rest parameter must be last formal parameter
SyntaxError array rest element: Rest element must be last element
SyntaxError object rest property: Rest element must be last element
SyntaxError lone comma in params: Unexpected token ','
SyntaxError lone comma in call: Unexpected token ','
SyntaxError parenthesized expression: Unexpected token ')'
ok arrow params
5 false [ 1, 2, 3, <2 empty items> ]
SyntaxError: Expected double-quoted property name in JSON at position 25 (line 1 column 26)
false true

(a, b,) is fine as arrow parameters but (1, 2,) is a syntax error as a parenthesized expression. In arrays, each comma beyond the first trailing one adds a hole. In a regex, {3,} means “three or more”.

In practice nobody adds trailing commas by hand: the formatter does it. Since version 3.0, Prettier formats multi-line arrays, objects, parameters, arguments, imports and exports with trailing commas by default (trailingComma: "all"; the default was "es5" before); "es5" limits them to places valid in ES5, and "none" removes them. Single-line lists never get one. An OrdersPortal team on the default gets the smaller diffs above without a style discussion (confirmed with Prettier 3.10.1). ESLint’s core comma-dangle rule is deprecated in favor of the @stylistic plugin.

Configuration files are the exception. package.json, tsconfig.json read by strict JSON parsers, and API payloads are JSON, where a trailing comma is a parse error. Some tools accept JSON with comments and trailing commas (TypeScript’s tsconfig.json parser does; checked with TypeScript 5.9), but do not rely on that for files that other programs read.

  • Copying a trailing comma into JSON. JSON.parse and most JSON tools reject it. Keep .json files strict.
  • Adding a comma after a rest element. (...args,), [a, ...rest,] and { ...rest, } in patterns are syntax errors, because nothing can follow a rest element.
  • Double commas in arrays. [a, b,,] creates a hole that map and forEach skip, which leads to confusing results.
  • Targeting old runtimes. Parameter and argument trailing commas are syntax errors before ES2017 support (for example Internet Explorer). The whole file fails to parse, so compile them away if you still ship to such runtimes.

Use trailing commas in every multi-line list in source code, ideally enforced by a formatter. Leave them out of single-line lists, where they add noise (formatters do this automatically), out of JSON and any data format with stricter rules, and out of code that must parse on engines older than ES2017.

According to MDN’s browser compatibility data, trailing commas in object literals work in every browser including Internet Explorer 9 and Node.js 0.10. Trailing commas in function parameters and calls need Chrome 58, Edge 14, Firefox 52, Safari 10 or Node.js 8.0.0 (Deno 1.0 and Bun 1.0 support them; Internet Explorer never did). A trailing comma in dynamic import() needs Chrome 91, Firefox 138, Safari 15 or Node.js 17.5.0. Babel and TypeScript remove trailing commas when they compile to older targets.

1. Does a trailing comma in a parameter list change the function’s behavior? No. function f(a, b,) {} has f.length === 2 and the same arguments as without the comma. It is purely syntax, added in ES2017.

2. What is the length of [1, 2, , ]? Three. The first trailing comma is ignored and the extra comma adds one hole at index 2.

3. Why does JSON.parse('[1, 2,]') fail when the same text is valid JavaScript? JSON has its own, stricter grammar defined in ECMA-404 and RFC 8259, and that grammar has no trailing commas. JSON.parse follows it, not the JavaScript grammar.

4. Senior scenario: a team argues about trailing commas in code review. What do you propose? Make it a formatter decision, not a review topic: adopt Prettier’s default trailingComma: "all" (or "es5" if the code must parse on pre-ES2017 engines without compilation), run it in a pre-commit hook and in CI, and reformat the codebase in one dedicated commit listed in .git-blame-ignore-revs so blame views skip it (GitHub reads that file automatically; locally, set git config blame.ignoreRevsFile .git-blame-ignore-revs).

  • Trailing commas are optional and never change run-time behavior, with two traps: extra commas in arrays create holes, and {n,} in regex means “n or more”.
  • Arrays: always; objects: ES5; destructuring and module lists: ES2015; parameters and arguments: ES2017; import(): ES2025.
  • Not allowed after a rest element or in JSON.
  • Let a formatter apply them consistently.