JavaScript Function Chaining
Let’s explain this using the “three-line theory” with three examples.
Get Abhishek sojitra’s stories in your inbox
Join Medium for free to get updates from this writer.
Three-Line Theory:
- 🚀 Start with an object: Begin with an object or value you want to operate on.
- ➡️ Chain functions: Chain one or more functions or methods that manipulate the object.
- ✨ End result: The final result of the chained operations is the return value or modified object.
Example 1 — 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 the doubled numbers
console.log(result); // Output: 12In this example:
- We start with the
numbersarray. - We chain three array methods to filter, map, and reduce the array.
- The final result is the sum of the doubled even numbers, which is
12.
Example 2 — Chaining String Methods:
const text = " Hello, World! ";
const result = text
.trim() // Remove leading and trailing spaces
.toUpperCase() // Convert to uppercase
.replace('WORLD', '🌍'); // Replace 'WORLD' with an emoji
console.log(result); // Output: "HELLO, 🌍!"In this example:
- We start with the
textstring. - We chain three string methods to trim, uppercase, and replace parts of the string.
- The final result is the modified string, which is
"HELLO, 🌍!".
Example 3 — Chaining Custom Functions:
class Calculator {
constructor(value) {
this.value = value;
}
add(num) {
this.value += num;
return this;
}
subtract(num) {
this.value -= num;
return this;
}
getValue() {
return this.value;
}
}
const calc = new Calculator(10);
const result = calc
.add(5) // Add 5
.subtract(3) // Subtract 3
.getValue(); // Get the final value
console.log(result); // Output: 12In this example:
- We start with an instance of the
Calculatorclass. - We chain custom methods to add and subtract values, and then get the final value.
- The final result is the calculated value, which is
12.
Chaining functions is a powerful way to streamline code and perform multiple operations in a clean and readable manner. 🌟
Stackademic
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us on Twitter(X), LinkedIn, and YouTube.
- Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.









