0

var e = 10;

function sum(a) {
    return function(b) {
        return function(c) {
            return function(d) {
                return a + b + c + d + e;
            }
        }
    }
}

console.log(sum(1)(2)(3)(4)); //logs 20

I'm not quite sure how to read this. It was one of the examples in some MDN documentation. Do you think it would be possible to give a step-by-step narration of what's going on?

Here's what I think is happening:

I thought sum(1) would return function(b) (which returns function(c) which returns function(d) which returns 1 + undefined + undefined + undefined + 10) but this is obviously wrong.

  • This approach is called as a Currying function – Rajesh Jul 27 '20 at 15:28
  • And to add to explanation, yes `sum` would return a function. But if you notice, you have parenthesis `()` after it. So it will call the return value and so on. Now why you would do it, answer is abstraction. Imagine a scenario of encryption. You create a function that takes your private key and return a function. This function takes a message and decrypts it. Now you do not wish to expose your private key. So you return this function which has access to your key but consumer is oblivious to it. – Rajesh Jul 27 '20 at 15:38

0 Answers0