How to make a chainable function with JavaScript?

Sometimes, we want to make a chainable function with JavaScript.

In this article, we’ll look at how to make a chainable function with JavaScript.

How to make a chainable function with JavaScript?

To make a chainable function with JavaScript, we can return this in our methods.

For instance, we write:

const obj = {
  foo() {
    this.foo = 'foo';
    return this;
  },
  bar() {
    this.bar = 'bar';
    return this;
  }
}
obj.foo().bar()
console.log(obj)

to define the obj object that had the foo and bar methods that sets the value of this.foo and this.bar respectively and returns this.

Since this is obj, we can call foo and bar by chaining them.

As a result, obj is {foo: 'foo', bar: 'bar'} after we run obj.foo().bar().

Conclusion

To make a chainable function with JavaScript, we can return this in our methods.