Understanding method chaining in Javascript


Often, we might encounter actions which includes a series of smaller individual actions. It's not that bad idea to put them all together in a single method when they are in lesser in number. But, when they are more such actoins it will be super messy and difficult to understand. So, it's preferred to have seperate methods for each such individual methods which increases readability and to avoid redundancy.

In Javascript, we can call methods after one another on a single object reference which is called method chaining or cascading.

objectName.method1().method2().method3();

The below example uses the built-in array functions like filter(), map() and reduce() which are called on the array numbers

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

const squaresOfEvenNumbers = numbers
.filter(ele => ele % 2 == 0)
.map(ele => ele ** 2)
.reduce((acc, ele) => acc + ele);

console.log(squaresOfEvenNumbers);

Similarly, you can also use the concept of method chaining on your own functions:

class methods {

  method1() {
    console.log("im method1");
   return this; 
  }
  
  method2() {
    console.log("im method2");
    return this;
  }
  
  method3() {
    console.log("im method3");
    return this;
  }
  
}

const m = new methods().method1().method2().method3();