-1

I have to write a single function that must be invoked by either

sum(2,3); //5 
//or
sum(2)(3); //5

I write this piece of code

function sum (a,b){
return a + b;
}
sum(2,3);

And I get the 'TypeError: number is not a function'. Why?

  • 1
    *"I have to write a single function that must be invoked by either"* Why? And separately: You can't (reasonably) do that. – T.J. Crowder Aug 29 '15 at 11:13
  • Executing it as `sum(2,3)` will *not* give the TypeError as you described!! Guess you meant: `sum(2)(3)`. Regarding your literal question **why**: Your current function returned a number (number a + number b is a number.. If (one of the) arguments was a string, then you would have gotten a string in return, which...*also* isn't a function). Then you tried to execute `()` this returned number (which is not a function), passing argument value `3`. But since the number is not a function, all you got was a TypeError... Yes, I couldn't help myself, but then again.. you asked the question "why"... – GitaarLAB Aug 29 '15 at 14:02

3 Answers3

1

You can do something like:

function sum(a,b) {
   return arguments.length>1? a+b : function (b) { return a + b };
}
Hazem
  • 107
  • 4
Amir Yahalom
  • 156
  • 2
1

You should use curried functions:

function sum(a, b) {
  if (b === undefined) {
    return function (b) {
      return a + b;
    }
  }
  return a + b;
}

// sum(1, 2) === sum(1)(2)
Vidul
  • 10,128
  • 2
  • 18
  • 20
  • currently best answer. Svend Tofte used to write about it quite some time ago, which was picked up by mr. Crockford and he copied the article, good read: http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html. Edit: *practical use*: http://stackoverflow.com/questions/113780/javascript-curry-what-are-the-practical-applications. Essentially this is just using *closures* to implement the concept. One can also use `new Function` by the way. – GitaarLAB Aug 29 '15 at 13:44
-1

You can only call the function in this manner.

sum(2,3);
Tabish
  • 1,592
  • 16
  • 13