Method Chaining in JavaScript Simplified

Method Chaining in JavaScript Simplified

Best practices for writing clean JavaScript code

Table of contents

Learning programming is one thing, following best practices while coding is another thing. As a good practice, it is expected that when you write functions or methods, a method should do one specific task.

While you may be tempted to write a single method that performs all the tasks you want, it is recommended that the best practices should be followed.

Disintegrate giant function into multiple functions so that each one performs a specific action. This simplification helps you write clean and readable code.

Method Chaining

This is a programming approach that helps you call methods on top of each other. This also helps you simplify your code.

With this strategy, you don't have to worry about writing one big function to perform a specific task. You can just write independent functions and chain them. Before we look at examples, let's look at what the this keyword is in JavaScript.

this keyword references the current object in which it is called. When the this keyword is returned in a method, it simply returns an instance of the parent object.

function a () {
   return this;
 }

// In a browser
a() === window // true

// In nodeJs
ab() === global // true

The function above returns true because of its current context which is the window object for the browser and global for nodeJs environments.

Let's look at the use strict mode which returns undefined if the value of this is not set before entering the function.

function a () {
  'use strict'; // see strict mode
   return this;
 }

ab() === undefined; // true

// In a browser
a() === window; // false

// In nodeJs
ab() === global; // false

We have looked at the this in the functional context, now let's understand how this behaves in the JavaScript class context.

The this keyword behaves similarly in classes and functions since classes are like functions under the hood in JavaScript but there are few differences.

Within classes, all properties of the class constructor are added to the this context.

More examples:

class ArithmeticClass {
  constructor() {
    this.value = 0;
  }

// get value
  get getValue() { 
    return this.value
   };

  sum(...args) {
    this.value = args.reduce((sum, current) => sum + current, 0);
    return this;
   }

  add(value) {
    this.value = this.value + value;
    return this;
   }
  subtract(value) {
    this.value = this.value - value;
    return this;
  }
  average(...args) {
    this.value = args.length? (this.sum(...args).value) / 
  args.length: undefined;
    return this;
  }
}


const ArithmeticClass1= new ArithmeticClass();
const firstArithmeticInstance = ArithmeticClass1
  .sum(1, 3, 6)   // => { value: 10 } 
  .subtract(3)   // => { value: 7 }
  .add(4)        // => { value: 11 }
  .getValue        // => 11 

console.log(firstArithmeticInstance) // => 11

This clearly shows you how each method in the ArithmeticClass returns the instance of the class which can be chained to any other method in the class.

While we can write a giant function that takes in a value/values, and the type of arithmetic operation we want to perform e.g. sum, and then probably use the if statement to perform any of the actions we want, Writing it the way we did above simplifies our code, makes it more readable and also, makes it more scalable in the future.