Course contentsShow
← JavaScript
Lesson 596 of 2,72315. ObjectsFree lesson

Trailing Commas and Readability

Use trailing commas in object literals for cleaner diffs and easier editing.

What You'll Learn

You'll learn how adding an optional trailing comma after the last property in an object literal makes your code easier to maintain and produces cleaner version control diffs.

Why Trailing Commas Matter

When you write an object literal, JavaScript allows you to place a comma after the last property. This might seem pointless at first—after all, there's nothing following it—but it's a powerful tool for code maintenance.

const person = {
  name: "Alice",
  age: 30,
  city: "Boston",  // ← trailing comma
};

The Real-World Benefit

Imagine you're adding a new property to your object. Without a trailing comma, you must modify two lines:

// Before
const person = {
  name: "Alice",
  age: 30,
  city: "Boston"  // ← must add comma here
  hobby: "Coding"  // ← AND add this line
};

With a trailing comma, you only touch one line:

// Before
const person = {
  name: "Alice",
  age: 30,
  city: "Boston",  // ← already has comma
  hobby: "Coding"   // ← just add this line
};

Version Control and Diffs

When reviewing code changes in Git or other version control systems, the trailing comma approach shows exactly what changed—only the new property. Without it, the diff shows both the comma addition and the new property, making reviews slightly noisier.

Think of it like: trailing commas are like keeping an extra chair at the dinner table. You don't need it until someone new arrives, but having it ready makes seating easier.

Key Takeaway: Always use trailing commas after the last property in object literals—it makes adding, removing, and reordering properties cleaner and produces more readable version control diffs.