Javascript: How to create chainable functions

What is the need to chain a function?

Functions are the first-class citizens in javascript. Every method or pattern implementation is done through functions. Many times in programming, we face a situation where we need to call a series of functions one after the other, passing the value from one step to the next step. Normally, handling such a sequence of function calls looks something like this:

const finalResult = function1(
function2(
function3()
)
);

OR

const result3 = function3();
const result2 = function2(result3);
const finalResult = function1(result2);
  1. Pattern-one would lead to callback hell, resulting in unreadable code.
  2. Pattern-two would lead to unnecessary variables stored in memory, leading to a slow, unresponsive website.
var arr = [10, 20, 33, 45, 56, 60, 70, 46, 23, 34, 98, 67];

var doubleArr = arr.filter(val => val > 50).map(val => val*2);
// (5) [112, 120, 140, 196, 134]

This — makes chainable functions possible

In javascript, the keyword this acts as a reference to the object which is being executed in the current context. The next piece of the article assumes that you are familiar with this and how it works in javascript. To understand more, refer to Javascript understanding this

function function1() {
console.log("i am function 1");
return this;
}

function function2() {
console.log("i am function 2");
return this;
}

function function3() {
console.log("i am function 3");
return this;
}

function1().function2().function3();
class Roots {
constructor() {
this.value;
}

data(val) {
this.value = val;
return this;
}

sq() {
var val = this.value
this.value = val*val;
return this;
}

cube() {
var val = this.value
this.value = val*val*val;
return this;
}

sqRoot() {
this.value = Math.sqrt(this.value);
return this;
}
}

var calculate = new Roots();
var result = calculate.data(2).sq().cube().sqRoot();
// result = { value: 8 }