Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Understanding Method Chaining 
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024

Method Chaining

Author Rajat Agrawal
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Method Chaining is a programming technique for making your code easier to read and understand. It's a mechanism for invoking one object's method on another object's method.

As a good programming practice, individual functions/methods should be written for dealing with individual actions. It's also possible to write a single method/function for all activities. On the other hand, sticking to best practices has a cost in terms of readability and comprehensibility because writing a different function for each action means that the output of a single function/method is input. The function must be nested in reverse order, making code comprehension more difficult. Method Chaining helps to solve this issue.

Let’s learn about Method Chaining in-depth.

Understanding Method Chaining 

Method chaining is calling one object's method on another object's method. It results in a more readable and cleaner code. To access the object's methods, method chaining employs this keyword in the object's class. This keyword in Javascript refers to the current object in which it is used. This keyword is merely an instance of the object in which it is returned when a method returns it. To put it another way, we need to make sure that every method we define has a return value so that we may call another method on it.

Let’s understand method chaining with the help of code examples:

Take the following class Bike, for example:-

class Bike {
    constructor() {
        this.wheels = 2
        this.model = "Pulsar"
        this.topSpeed = 150
        this.fuelCapacity = "6 Litres"
    }
    setWheels(wh) {
        this.wheels = wh
    }
    setModel(m) {
        this.model = m
    }
    setTopSpeed(t) {
        this.topSpeed = t
    }
    setFuelCapacity(fc) {
        this.fuelCapacity = fc
    }
    displayBikeProps() {
        console.log(`The Bike has ${this.wheels} wheels, ${this.model} model with a top speed of ${this.topSpeed}, and fuel capacity of ${this.fuelCapacity}`)
    }
}
let sportsBike = new Bike();
sportsBike.setWheels(2)
sportsBike.setModel("Yamaha")
sportsBike.setTopSpeed(200)
sportsBike.setFuelCapacity("8 Litres")
sportsBike.displayBikeProps()

Output: 

You can see how many times sportsBike is unnecessarily repeated. To get rid of this repetition, we can use the method chaining. Instead of letting the setters just set the value, return this at the end. This will allow us to perform operations on the object. 

After making the changes, the code will look like the below:-

class Bike {
    constructor() {
        this.wheels = 2
        this.model = "Pulsar"
        this.topSpeed = 150
        this.fuelCapacity = "6 Litres"
    }
    setWheels(wh) {
        this.wheels = wh
        return this
    }
    setModel(m) {
        this.model = m
        return this
    }
    setTopSpeed(t) {
        this.topSpeed = t
        return this
    }
    setFuelCapacity(fc) {
        this.fuelCapacity = fc
        return this
    }
    displayBikeProps() {
        console.log(`The Bike has ${this.wheels} wheels, ${this.model} model with a top speed of ${this.topSpeed}, and fuel capacity of ${this.fuelCapacity}`)
    }
}
let sportsBike = new Bike();
sportsBike.setWheels(2)
    .setModel("Yamaha")
    .setTopSpeed(200)
    .setFuelCapacity("8 Litres")
    .displayBikeProps()

Output: 

We can see how with the help of method chaining, the repetition of sportsBike gets reduced and code becomes more efficient and readable. For practice try it by yourself on an online javascript compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

FAQs

1. Define Method Chaining.

Method chaining is calling one object's method on another object's method. It results in a more readable and cleaner code.

2. What is the significance of ‘this’ keyword in Javascript?

This keyword in javascript refers to the current object in which it is used. This keyword is merely an instance of the object in which it is returned when a method returns it.

3. Define Function Chaining.

Function chaining is nothing but grouping functions in one single line using dot notation.

Key Takeaways

In this article, we have extensively discussed Method Chaining in JavaScript and the use of Method Chaining. If you want to learn more, check out our articles on An Introduction to JavascriptObject Prototype, and Function Composition.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Previous article
JS Currying
Next article
JavaScript eval() function
Live masterclass