Skip to content

Chaining Methods

Method chaining is writing several method calls one after another in a single expression, as in a.first().second().third(). Each call runs on whatever the previous call returned, so a chain works only when every method except the last returns an object.

To make an object’s own methods chainable, each method that changes the object ends with return this, which hands the same object on to the next call:

class Order {
constructor() {
this.lines = [];
this.discount = 0;
}
add(name, price) {
this.lines.push({ name, price });
return this;
}
applyDiscount(percent) {
this.discount = percent;
return this;
}
total() {
const gross = this.lines.reduce((sum, line) => sum + line.price, 0);
return gross * (1 - this.discount / 100);
}
}
const total = new Order()
.add('Kettle', 30)
.add('Toaster', 25)
.applyDiscount(10)
.total();
console.log(total);

This prints:

49.5

total() returns a number rather than the object, so it has to come last. Putting each call on its own line, starting with the dot, keeps a long chain readable.

A method without a return statement returns undefined, and the next call in the chain then fails:

class Order {
constructor() {
this.lines = [];
}
add(name, price) {
this.lines.push({ name, price });
}
}
try {
new Order().add('Kettle', 30).add('Toaster', 25);
} catch (err) {
console.log(err.message);
}

This prints:

Cannot read properties of undefined (reading 'add')

Many built-in methods return a value that can be chained. Array methods such as filter(), map() and toSorted() each return a new array, so a chain can take a list through several steps without changing the original:

const books = [
{ title: 'Middlemarch', pages: 880, read: true },
{ title: 'Ivanhoe', pages: 544, read: false },
{ title: 'Cranford', pages: 256, read: false },
{ title: 'Persuasion', pages: 249, read: false },
];
const toRead = books
.filter((book) => !book.read)
.toSorted((a, b) => a.pages - b.pages)
.map((book) => `${book.title} (${book.pages} pages)`)
.join('\n');
console.log(toRead);

This prints:

Persuasion (249 pages)
Cranford (256 pages)
Ivanhoe (544 pages)

This is a different kind of chain from the Order one, because each step returns a new array instead of the same object. sort() would also work in this chain, but it sorts the array in place, so at the start of a chain it would reorder the original. toSorted(), added in ES2023, always returns a sorted copy. Chaining Array and Arrow Functions has more examples.

A chain suits a builder, such as the Order above or a query builder, where several settings are applied before one final call. It is harder to debug than separate statements, because there is no variable to inspect between steps. A short chain reads well, and a long one is often clearer split into named steps.

Steve Griffith covers this topic in his video How to Chain JS Methods Together.