2

From this documentation on closures:

function makeAdder(x) { return function(y) { return x + y; }; } var add5 = makeAdder(5); var add10 = makeAdder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12 

I can't understand how in makeAdder(5) the parameter is received as x, but in add5(2) it is y.

I would expect it to say y is undefined both times. Can anyone explain how it works the way it does?

5
  • I just realized it can be called like makeAdder(5)(2) which now makes sense, but I'll leave the question in case someone can explain it for future users. Commented Aug 29, 2017 at 14:54
  • 2
    This is also known as currying. The exact same code can be found here: stackoverflow.com/questions/36314/what-is-currying Commented Aug 29, 2017 at 14:55
  • this is a duplicated question of another... Commented Aug 29, 2017 at 14:55
  • @Endless then tag it as such with a link to the other question? Commented Aug 29, 2017 at 14:57
  • There is no way that is a duplicate question. Even if I had found that, it would only have confused me further. It is way more complex and references third party libraries and paradigms (arrow functions) not even mentioned here. Commented Aug 29, 2017 at 16:43

3 Answers 3

2

When you call makeAdder() it returns a function (not a value). Therefore to use it, you would have something like

makeAdder(4)(5) 

This would add 4 to 5 and return 9. Again, makeAdder() here returns another function, which is why I called an argument after it ((5)).

If you would like to read further, this is a concept in JavaScript which is called currying. It is a functional programming technique.

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

1 Comment

That is so nice to hear. Thank you very.
1

When calling add5 = makeAdder(5); essentially what is happening is:

add5 = function(y){ return 5 + y; } 

At this point add5(y) will give you y + 5.

As you've noticed from your comment you can use makeAdder(x)(y), this essentially does the same thing, it boils down to:

(function(y){return x + y})(y); 

Comments

0

makeAdder takes a parameter x, and returns a function that can see x (google: "closure") and also takes its own parameter, y.

Comments