DEV Community

Cover image for Method Chaining in JavaScript
Indrakant Mishra
Indrakant Mishra

Posted on

1 1

Method Chaining in JavaScript

Hello,
In this article we will see how we can chain methods in javascript. This is most commonly asked questions in interviews for front end developers. An example of it could be person.walks().talks().laughs().listens()

We can chain this till any level, let's see this in code:

class Person{
    constructor(name){
        this.name = name;
    }
    walks(){
        console.log(this.name +' Walks')
        return this;
    }
    talks(){
        console.log(this.name +' Talks')
        return this;
    }
    laughs(){
        console.log(this.name +' Laughs')
        return this;
    }
}

let person = new Person('Person 1');
person.walks().talks().laughs();

//Output: 
Person 1 Walks
Person 1 Talks
Person 1 Laughs
Enter fullscreen mode Exit fullscreen mode

Here, return this helps in chaining the methods which passes the complete object with all of it's prototypes and with that we can chain the methods.

*Hope you liked it, please mention in comment for any suggestions or feedback *

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay