js Advanced
Method chaining
Open this example in our interactive code editor to experiment with it.
Try the EditorChain them all
// Let's count vowels in a string using the method chaining
const VOWELS = ['a', 'e', 'i', 'o', 'u'];
// Reduce an array of letters to get the sum of vowels
// and pass a function to .reduce method to make it more readable
const countVowels = (sum, letter) => (VOWELS.includes(letter) ? ++sum : sum);
// 1. .replace returns a string without whitespaces
// 2. .split returns an array of letters
// 3. .reduce reduces an array of letters into a single number - the sum of vowels
const getVowelsCount = (string) =>
string.replace(/ /g, '').split('').reduce(countVowels, 0);
Summary
- Method chaining is a really good pattern for avoiding repetition and making your code more readable.
- It plays well with functional programming and is often used in JavaScript.
- Each of the methods needs to return something in order to call another method on it. Hence the chaining name.
Try this in our interactive code editor
Practice hands-on with our built-in code sandbox.
Open Code Editor
Adrian Bigaj
Creator of BigDevSoon
Full-stack developer and educator passionate about helping developers build real-world skills through hands-on projects. Creator of BigDevSoon, a vibe coding platform with 21 projects, 100 coding challenges, 40+ practice problems, and Merlin AI.
Related Pills
js Advanced
Immutable add, edit, delete operations
Learn how to add, edit and delete array of objects in semantic, declarative approach using rest spread operator and array methods.
js Intermediate
JavaScript multiple condition checks
Checking multiple values in JavaScript often leads to redundant, boilerplate code - let's use .includes method to fix that.
js Intermediate
Convert JavaScript data structures
Converting data structures is a day-to-day job as a Developer.