Closure in JavaScript – whats wrong?

You somehow have to signalize the end of the chain, where you are going to return the result number instead of another function. You have the choice:

  • make it return a function for a fixed number of times – this is the only way to use the syntax like you have it, but it’s boring. Look at @PaulS’ answer for that. You might make the first invocation (func(n)) provide the number for how many arguments sum is curried.
  • return the result under certain circumstances, like when the function is called with no arguments (@PaulS’ second implementation) or with a special value (null in @AmoghTalpallikar’s answer).
  • create a method on the function object that returns the value. valueOf() is suited well because it will be invoked when the function is casted to a primitive value. See it in action:

    function func(x) {
        function ret(y) {
            return func(x+y);
        }
        ret.valueOf = function() {
            return x;
        };
        return ret;
    }
    
    func(2) // Function
    func(2).valueOf() // 2
    func(2)(3) // Function
    func(2)(3).valueOf() // 5
    func(2)(3)(4)(5)(3) // Function
    func(2)(3)(4)(5)(3)+0 // 17
    

Leave a Comment