Published on

How to chain functions in JavaScript

Thumbnail

When using a library such as express-validator, we might encounter a syntax like this:

body('email').isEmail().withMessage('Email is required')

The interesting part here is that we can chain the isEmail method to the withMessage method.

I wondered how this is possible, and after a small research, I found the way to chain functions in JavaScript.

Basic Example

function operator(initial) {
  return {
    current: initial,
    add(n) {
      this.current += n
      return this
    },
    subtract(n) {
      this.current -= n
      return this
    },
    divide(n) {
      this.current /= n
      return this
    },
    multiply(n) {
      this.current *= n
      return this
    },
  }
}

// example usage
const result = operator(10).add(18).subtract(7).multiply(2)
console.log(result.current) // => 42

This example contains all the necessary information for you to understand how to chain functions.

How it Works

When we first call the operator function, it actually returns an object with current set to the initial value and several predefined functions.

Just like a normal object, we can access our current value with obj.current and call our functions with obj.func().

In order to chain our functions, we need to return the current instance after each function call so that the next function can use that instance as well.

multiply(n) {
 this.current *= n;
 return this; // must return the current instance
}

We shouldn't use the arrow functions as it does not have its own binding to this!

That's it!

It was a magical feature for me until learning how easy it was. Hope this post helps you to understand how to chain functions.