Five Different Ways of Using Functions

Ben Butler
Aug 27, 2021

These are a few of the many ways of doing the same thing in JavaScript

Imperative

function add1(){ return 1; }
function add2(){ return 2; }
function add3(){ return 3; }
console.log(1 + add1() + add2() + add3());

Composing

function add1(num){ return num+1; }
function add2(num){ return num+2; }
function add3(num){ return num+3; }
console.log(add1(add2(add3(1))));

Currying

function add1(num){ return add2(num+1);}
function add2(num){ return add3(num+2);}
function add3(num){ return num+3;}
console.log(add1(1));

Callback

function add1(num, fun) { return fun(num,add3)+1; }
function add2(num, fun) { return fun(num)+2; }
function add3(num) { return num+3; }
console.log(add1(1, add2));

Object

function Number(value){ 
this.value = value;
this.getResult = function(){ return this.value }
this.add1 = function(){ return new Number(this.value+1); }
this.add2 = function(){ return new Number(this.value+2); }
this.add3 = function(){ return new Number(this.value+3); }
}
console.log(new Number(1).add1().add2().add3().getResult());

--

--