Sitemap

Function chaining in Js

Jan 29, 2022

--

Function chaining is nothing but grouping functions in one single line using dot notation.

var Math = function(initialValue){
this.initialValue = initialValue;

this.add = function(i){
this.initialValue = this.initialValue + i
return this;
};
this.subtract = function(i){
this.initialValue = this.initialValue - i
return this;
};

Get Sourabh Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

this.multiply = function(i){
this.initialValue = this.initialValue * i
return this;
};

this.divide = function(i){
this.initialValue = this.initialValue / i
return this;
};
this.done = function(){
return this.initialValue
}
}

function main() {
const x = new Math(10);
if (x.add(3).multiply(2).add(4).subtract(6).divide(4).done() === 6) {
console.log(‘true’);
} else {
console.log(‘false’);
}
}
main();

Disclaimer — Question asked in Paypal Interview🤓!

--

--

Sourabh Kumar
Sourabh Kumar

Written by Sourabh Kumar

Founding Engineer @ StableMoney, Ex-Lenskart | Graduated from BIT Mesra