DEV Community

Cover image for Method Chaining - JavaScript
umerjaved178
umerjaved178

Posted on

Method Chaining - JavaScript

Chaining Method (also known as Cascading), means repeatedly calling one method after another on an object, in one continuous line of code eventually reducing the redundancy. (Skyrocketing the code quality 🚀)

If you don’t know jQuery then ignore the next line 😉

You will also understand the concept of functional training in jQuery And how we mimic the same behaviour in Javascript

Let's get started

class User {
  constructor(username) {
    this.username = username;
    this.score = 0;
  }
  login() {
    console.log(this.username, "has logged in");
  }
  logout() {
    console.log(this.username, "has logged out");
  }
  updateScore() {
    this.score++;
    console.log(this.username, "score is now", this.score);
  }
}

let noemi = new User("Noemi");
let jack = new User("Jack");

// Run it in Browser

noemi.login() 
// "noemi has logged in"
// undefined

noemi.updateScore() 
// "noemi score is now 1"
// undefined

Enter fullscreen mode Exit fullscreen mode

We also get the undefined because our methods are not returning any value.

Let's chain it now

noemi.login().updateScore()

//console
//Noemi has logged in
//Uncaught TypeError: Cannot read property 'updateScore' 
//of undefined
//    at <anonymous>:1:14
Enter fullscreen mode Exit fullscreen mode

Why chaining is not working?
The reason is, methods run on the instance of object, as our methods are returning undefined, no instance is available for updateScore() to run on
*Solution: *
Simply, return instance of the object from methods, as we all know it is store in this

Updated code is

class User {
  constructor(username) {
    this.username = username;
    this.score = 0;
  }
  login() {
    console.log(this.username, "has logged in");
    return this; //new
  }
  logout() {
    console.log(this.username, "has logged out");
    return this; //new
  }
  updateScore() {
    this.score++;
    console.log(this.username, "score is now", this.score);
    return this; //new
  }
}

let noemi = new User("Noemi");
let jack = new User("Jack");

// Run it in Browser

noemi.login() 
// "noemi has logged in"

noemi.updateScore() 
// "noemi score is now 1"

Enter fullscreen mode Exit fullscreen mode

Let's chain it again

noemi.login().updateScore()

//console
//Noemi has logged in
//Noemi score is now 1

noemi.login().updateScore().logout() //chain as many methods as you want
Enter fullscreen mode Exit fullscreen mode

Conclusion:

You can also chain methods using objects, do you guys want that implmentation too?

Top comments (1)

Collapse
 
jjablonskiit profile image
Jakub Jabłoński

This can be explained nicely on the builder pattern as it's pretty much essential there. Not much applications but still neat trick to know