AI Hints
Home›JavaScript Tutorial›Modern Array Tools
JavaScript · Lesson 52 of 138

Chaining Methods

Map, filter, reduce together.

⏱ 2 min read▶ Video at 1:03:20🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Map, filter, and reduce each return a value you can keep working with. So you can chain them, one after another, like steps on a production line. It's one of the most elegant things in JavaScript.

Chaining Methods
From the video: Chaining Methods
  • Each returns a value
  • Chain them together
  • A production line

A production line

Here's an order. First, filter keeps only the items in stock. Then map works out the cost of each line, price times quantity. Finally, reduce adds those up. Each step reads like a sentence. Run it.

app.jsjavascript
const order = [
  { name: "pen", price: 2, qty: 3, inStock: true },
  { name: "book", price: 12, qty: 1, inStock: true },
  { name: "lamp", price: 30, qty: 1, inStock: false },
];

const total = order
  .filter(item => item.inStock)
  .map(item => item.price * item.qty)
  .reduce((sum, cost) => sum + cost, 0);

console.log("Total:", total);
Output
Total: 18

Readable chains

Put each step on its own line, starting with the dot. Then the chain reads from top to bottom. Keep each callback short. If a step gets complicated, give it a name, by moving it into its own function. We'll learn more about objects like these order items soon.

keyvalue
filterchoose items
maptransform them
reducecombine them
One step per lineeasy to read

Summary

Chain filter, map, and reduce to build a clear production line of steps. Next, the spread and rest operators.

Key takeaways
  • filter → map → reduce
  • One step per line
  • Short callbacks
Next up: Spread and Rest — three little dots