DEV Community

Cover image for Method Chaining - JavaScript
umerjaved178
umerjaved178

Posted on

2

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?

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️