user13538959
user13538959

Reputation:

How to write a function which can accept one or more arguments and send back addition

I have to call function in below way

sum(3)(2)

My function is:

sum(a,b) { return a + b }

Upvotes: 1

Views: 84

Answers (2)

Soham
Soham

Reputation: 725

Take a look at Currying concept

let sum = (a) => (b) => a + b

console.log(sum(1)(3)) // 4

Upvotes: 4

kokila
kokila

Reputation: 294

you can try out this approach

function sum(x, y) {
 if (y !== undefined) {
  return x + y;
 } else {
  return function(y) { return x + y; };
 }
}

To understand it better https://www.toptal.com/javascript/interview-questions

Upvotes: 0

Related Questions