Skip to content

Chaining Array Methods & Arrow Functions

Array methods such as filter() and map() return a new array, so another array method can be called straight on the result. Writing the calls one after another is called chaining. Each step takes the previous step’s array and passes its own on, which lets a series of small operations read from top to bottom like a list of instructions.

To get the email addresses of the active members of a club, first keep the active members, then take each one’s email. With a variable for the middle step:

const members = [
{ name: 'Asha', email: 'asha@example.com', active: true },
{ name: 'Tom', email: 'tom@example.org', active: false },
{ name: 'Mei', email: 'mei@example.com', active: true },
];
const active = members.filter((member) => member.active);
const emails = active.map((member) => member.email);
console.log(emails);
console.log(members.filter((member) => member.active).map((member) => member.email));

This prints:

[ 'asha@example.com', 'mei@example.com' ]
[ 'asha@example.com', 'mei@example.com' ]

The last line does the same work without the active variable. Arrow functions keep each step short, because a single expression after => is returned without needing braces or return.

A longer chain is easier to read with each call on its own line, starting with the dot. This one turns a shopping basket into a receipt: it drops empty lines, works out each cost, sorts by cost from highest to lowest, formats each line and joins them into one string.

const basket = [
{ item: 'Bread', price: 1.45, quantity: 2 },
{ item: 'Coffee', price: 5.5, quantity: 1 },
{ item: 'Apples', price: 0.4, quantity: 6 },
{ item: 'Cheese', price: 3.2, quantity: 0 },
];
const receipt = basket
.filter((line) => line.quantity > 0)
.map((line) => ({ item: line.item, cost: line.price * line.quantity }))
.toSorted((a, b) => b.cost - a.cost)
.map((line) => `${line.item}: £${line.cost.toFixed(2)}`)
.join('\n');
console.log(receipt);

This prints:

Coffee: £5.50
Bread: £2.90
Apples: £2.40

toSorted(), added in ES2023, returns a sorted copy. The older sort() sorts the array it is called on in place, which is harmless in the middle of a chain but changes the original when it is the first call, so toSorted() is the safer habit. The chain can end in a method that returns something other than an array, such as join() or reduce(), but nothing can be chained after that.

The most common mistake in a chain is an arrow function with braces but no return. Braces make a function body, and a body returns undefined unless it says otherwise.

const members = [{ name: 'Asha' }, { name: 'Tom' }];
console.log(members.map((member) => { member.name; }));
console.log(members.map((member) => { return member.name; }));
console.log(members.map((member) => member.name));

This prints:

[ undefined, undefined ]
[ 'Asha', 'Tom' ]
[ 'Asha', 'Tom' ]

Steve Griffith covers this topic in his video JavaScript Chaining Array Methods and Using Arrow Functions.