0
    function sum(a) {
        var sum = a
        function f(b) {
            sum += b
            return f
        }

        f.toString = function () { return sum }
        return f
    }
    var a = sum(0)(1)(2)(3)(4)(5);

Can someone explain to me how does this code works? I really don't get how to call function with multiple closures in such a way. And why when i print a in the browsers console the result is "function 15" and not just 15

4
  • What part don't you understand? Commented Apr 13, 2016 at 16:10
  • There is only one closure here. Commented Apr 13, 2016 at 16:10
  • (0)- 1 closure (1)-2nd closure etc..? Commented Apr 13, 2016 at 16:19
  • No; those all return the same function (return f) Commented Apr 13, 2016 at 16:21

2 Answers 2

2

And why when i print a in the browsers console the result is "function 15" and not just 15

To get final result you should call toString function. This closure holds the sum until you call toString function.

function sum(a) {
    var sum = a

    function f(b) {
        sum += b
        return f
    }

    f.toString = function() {
        return sum;
    }
    return f
}

var a = sum(0)(1)(2)(3)(4)(5);

document.write(a.toString());

Sign up to request clarification or add additional context in comments.

Comments

2

sum(0) returns a function f that closes over the local variable sum (the only closure in that code). Because it returns a function it means you can call that function which also accepts an argument and returns itself which is how you can keep chaining like that.

sum(0) // `sum` is 0, returns f (a function)
sum(0)(1) // returns f which adds 1 to `sum` and returns f again
// and again etc

Another way of thinking about it:

var fn0 = sum(0) // `sum` is 0, returns f (a function)
var fn1 = fn0(1) // returns f which adds 1 to `sum` and returns f again
var fn2 = fn1(2) // ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.