Course contentsShow
← JavaScript
Lesson 808 of 2,72319. ArraysFree lesson

Trailing Commas in Array Literals

Learn that trailing commas after the last element are allowed and ignored.

Trailing Commas in Array Literals

You'll learn that JavaScript allows (and ignores) an extra comma after the last element in an array literal.

What Is a Trailing Comma?

When you write an array literal, you separate elements with commas. Interestingly, JavaScript permits you to place a comma after the last element as well—this is called a trailing comma (or "dangling comma"). The JavaScript engine simply ignores it.

const colors = ['red', 'green', 'blue',];
// That comma after 'blue' is allowed!

console.log(colors.length); // 3 (not 4!)
console.log(colors);        // ['red', 'green', 'blue']

Why Allow Trailing Commas?

This might seem odd at first, but trailing commas make code maintenance easier. When you add new elements to the end of an array, you don't need to modify the previous line to add a comma:

const fruits = [
  'apple',
  'banana',
  'cherry', // Trailing comma here
];
// If you add 'date' later, you only touch one line

What Trailing Commas Don't Do

A trailing comma does not create an empty slot. This is different from having multiple commas in a row (which you learned creates sparse arrays):

const withTrailing = [1, 2, 3,];   // Length: 3
const withEmpty = [1, 2, 3, ,];    // Length: 4 (empty slot at index 3)

Key Takeaway: Trailing commas after the last element in array literals are legal, ignored by JavaScript, and help keep code clean when adding or reordering elements.