js Advanced

Method chaining

Method chaining
Method Chaining Demo

Open this example in our interactive code editor to experiment with it.

Try the Editor

Chain 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
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.