DEV Community

Cover image for Method Chaining in JavaScript
Indrakant Mishra
Indrakant Mishra

Posted on

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 *

Top comments (0)