1

I just started learning closures in JavaScript and I'm trying to understand a basic problem.

For example, I'm trying to implement the sum method: sum(1)(4)(5)

const sum = (a) => {
    return (b) => {
        if(typeof b === 'number')
            return sum(a+b)
        return a;
    }
}

When I call: console.log(sum(1)(4)(5)()) it works perfect and return 10. However, if I call console.log(sum(1)(4)(5)), it returns [Function (anonymous)]. Why?

Thanks

user2792523
  • 57
  • 1
  • 6
  • in sum(1)(4)(5)() the last call causes if statement to be skipped and `return a` to be executed. However when you keep passing numbers into the function it goes into `return sum(a+b)` which then returns a new clojure – Ali Baykal Aug 20 '21 at 22:29
  • 1
    Because functions return different things when called differently – Dexygen Aug 20 '21 at 22:36
  • Btw when the intent is to implement a function which can take any amount of arguments like above, it becomes necessary to mark the end of the arguments. Which you do by the last empty call. So I don't think you can get rid of that last call. – Ali Baykal Aug 20 '21 at 22:38
  • @AliBaykal are you saying that there is no what to make it work without inserting the last parenthesis – user2792523 Aug 20 '21 at 23:00
  • @user2792523, yes – Ali Baykal Aug 20 '21 at 23:03

1 Answers1

1

Every time you call your function like:

sum(1)(10)

you are returning the inner function:

(b) => {
        if(typeof b === 'number')
            return sum(a+b)
        return a;
    }

Because type of b === 'number' and you are returning sum(a+b) that calls again the function sum and returns again the inner function. Thats why when you finally put the last parenthesis like:

sum(1)(10)()

The inner function will execute and type of b in this case is different from number and will return 'a' that already contains the sum of the values.

Castri1
  • 76
  • 1
  • 4
  • I know it. My question is, how can I make it work without inserting the last parenthesis – user2792523 Aug 20 '21 at 22:59
  • @user2792523 You can't, really. You have to return another function, to make another call with a number possible. – Bergi Aug 21 '21 at 15:02