DEV Community

akhilmdev
akhilmdev

Posted on

2 3

Method chaining & create a custom method chaining!

Function Chainging

    A common syntax for invoking mutiple method calls
Enter fullscreen mode Exit fullscreen mode

What ?

Function Chaining is a pattern in JavaScript where multiple functions are called on the same object consecutively.

We can understand the above definition with examples below.

Examples

1

const totalExpensesInINR = tripExpenses
                            .filter(expense => expense.paid)
                            .map(expense => {
                                if (expense.currency === 'USD') return expense.amount * 70;
                                else return expense.amount;
                            })
                            .reduce((amountA, amountB) => amountA + amountB, 0);

Enter fullscreen mode Exit fullscreen mode

Here the tripExpenses is an array of objects(expense), thus we can apply filter which is an array method and it returns array (find more about filter). Since filter return an array again we can call map which is an array method(find more about map) and so on the get the total of the expense in INR.

Here we call filer, map and reduce (multiple methods) on tripExpenses (same object) one after the other (consecutively) to get the require results.

2

const numbers = [2, 3, 5, 10];

const newNumbers = numbers
                    .map((number) => number * 2) // [4, 6, 10, 20]
                    .filter((number) => number > 5) // [6, 10, 20]
                    .join("0") // '6010020'
                    .split("") // ['6', '0', '1', '0', '0', '2', '0']
                    .map((ele) => Number(ele));

//[6, 0, 1, 0, 0, 2, 0]

// The object that return on previous method or initial object

Enter fullscreen mode Exit fullscreen mode

If you check the above examples we can see that after the join method (an array method which returns string). Since the previous method return a string, we can only use a string method to chain further. So we can rewrite the definition of method chaining to

Function Chaining is a pattern in JavaScript where multiple functions are called on the inital object for first method and object that returns on previous method for conecutive methods consecutively.

Why ?

1. Large number of parameters.

function maxParams(param1, param2, param3, ..., paramN) {
    // have some complex logic with params
}

// convert to mathod chaining

maxParamsObj.process1(param1)
            .process2(param2)
            ...
            .processM(paramN)

Enter fullscreen mode Exit fullscreen mode

2. Reduce to small and reusable unit(function).

3. Avoid intermidate variables.

const persons = [
    {name: 'Akhil', age: 29},
    {name: 'Nikhil', age: 32},
    {name: 'Deepak', age: 21}
]

const personsAgeGraterThan25 = persons.filer(person => person.age > 25);
const personNames = personsAgeGraterThan25.map(person => person.name);
const personNameStr = personNames.join(',')

// This can be done without intermidate variables

const personNameStr = person.filer(person => person.age > 25)
                            .map(person => person.name)
                            .join(',')

Enter fullscreen mode Exit fullscreen mode

4. Readable and maintainable code.

Why Not ?

1. Confuses the signature.

If a method used in chaining return another object, That make confusion and hard to identify as the code is abstracted.

2. Hard to debug.

How ?

Here we created a Recipe class where its has methods like sliceVegitables, addIngredient, boil etc... which return this (which is the instance of class itself). Thats why we can call the function with in the class as chain.
But in the case of serve method we are not return anything, So we won't be able to call any Recipe methods after the serve method is executed(we can call only the methods of undefined type).

Concusions

  • Function Chaining is a pattern in JavaScript where multiple functions are called on the inital object for first method and object that returns on previous method for conecutive methods consecutively.
  • For a custom Method chaining, we always return this from methods, so that we can chain the methods of same class.(If we return anything other than this, then we can only chain with the methods of corresponding type).

keep learning.

Thanks!

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay