-1

I defined a function let sum = a => b => b?(a+b):a;

If I do console.log(sum(1)(2)()); I get the output 3

But If I try console.log(sum(1)(2)(3)()); I get an error.

Why is that?

zer0
  • 4,657
  • 7
  • 28
  • 49
  • post the error that occurs – user2342558 Oct 10 '19 at 14:11
  • 3
    Because the function that `sum` returns doesn't return a function but a number. `b?(a+b):a` either returns `a+b` or `a`. Neither of these is a function in your example. – Felix Kling Oct 10 '19 at 14:11
  • Brause sum is a function and sum() is a function but sum()() is not a function – Joschi Oct 10 '19 at 14:13
  • 3
    Because `sum(1)(2)` returns `3`, the call `sum(1)(2)(3)` is like `3(3)`. Don't do that. – Bergi Oct 10 '19 at 14:13
  • https://stackoverflow.com/questions/58191104/sum23-and-sum2-3-what-is-the-common-solution-for-both/58191650 – Taki Oct 10 '19 at 14:14
  • Thanks guys! I got it it should have been `sum(a+b)`. I can't believe I missed that :) – zer0 Oct 10 '19 at 14:15
  • What would be `sum` without arrow functions? `function(a) { function(b) { function() { if (a) return a; else return a+b; } } }` ? Just to understand how that works – GrafiCode Oct 10 '19 at 14:16

1 Answers1

2

When you do

console.log(sum(1)(2)(3));

it will throw an error because you are trying to invoke the 3rd function; which you never created (sum(1)(2) returns 3, which isn't a function).

Your function is a higher order function of two order. A function that returns another function. So the function call should be twice only; you mustn't call the 3rd function, as you did above.

FZs
  • 16,581
  • 13
  • 41
  • 50
Emeka Augustine
  • 891
  • 1
  • 12
  • 17