Multiple bracket function in JavaScript

Multiple bracket function in JavaScript are tricky to understand. The bracket generally resemble a function without bracket it would be a variable. So, if you want multiple bracket function you would need to return multiple function in it. For eg: look at the code below.

function addThis(x){
   return function(y){
       return x+y;
   }
}
addThis(3)(4) //output : 7

Now what if we need to perform same operation with the number of bracket which is not fixed ?

addThis(3)(4) // 7
addThis(3)(4)(5) //12
addThis(3)(4)(5)(6) //18
addThis(1)(1)(1)(1)(1) //5

With single bracket function we could just have rest parameter.

 function add(...args) {
     let sum = 0;
     for(let i=0; i<args.length; i++) {
         sum  = sum + args[i];
     }
     return sum;
 }
console.log(add(1,2,3,4,5))

But with multiple bracket function we might need to use like this. You have to pass empty () at the end when you want to terminate the call and get the final value.

const sum= x => y => (y !== undefined) ? sum(x + y) : x;
sum(10)(30)(45)();

Credit Link

Leave a Reply

Your email address will not be published. Required fields are marked *