Method chains allow a series of functions
Source: Dev.to
Method chaining in JavaScript
Method chaining involves calling multiple methods sequentially on the same object or result. This pattern is common with array methods like filter, map, reduce, and others, where each method returns a new array or value, allowing the next method to operate on that result.
Example: chaining array methods
const numbers = [1, 2, 3, 4, 5];
const result = numbers
.filter(num => num % 2 === 0) // Filter even numbers
.map(num => num * 2) // Double each remaining number
.reduce((acc, num) => acc + num, 0); // Sum up the doubled numbers
console.log(result); // Outputs 18 (2*2 + 4*2 + 5*2)
How it works
Filter
Creates a new array containing only the even numbers from the original array.
Map
Doubles each number in the filtered array, producing another new array.
Reduce
Sums all the doubled numbers in the mapped array, resulting in a single value (18 in this case).
Example: chaining with an array of objects
let cart = [
{ name: "Drink", price: 3.12 },
{ name: "Steak", price: 45.15 },
{ name: "Drink", price: 11.01 },
];
const drinkTotal = cart
.filter(item => item.name === "Drink")
.map(item => item.price)
.reduce((total, price) => total + price, 0)
.toFixed(2);
console.log(`Total Drink Cost $${drinkTotal}`); // Total Drink $14.13
Benefits of method chaining
- Improved readability – the flow of data transformations is clear and linear.
- Reduced need for intermediate variables – each step returns a value for the next step.
- More declarative code – expresses what should happen rather than how to manage temporary state.
Happy coding! 🔥