3

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?

  • 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. –  Aug 29 '17 at 14:54
  • 2
    This is also known as currying. The exact same code can be found here: https://stackoverflow.com/questions/36314/what-is-currying – byxor Aug 29 '17 at 14:55
  • this is a duplicated question of another... – Endless Aug 29 '17 at 14:55
  • @Endless then tag it as such with a link to the other question? –  Aug 29 '17 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. –  Aug 29 '17 at 16:43

3 Answers3

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.

Y2H
  • 2,419
  • 1
  • 19
  • 37
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);
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
0

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

cHao
  • 84,970
  • 20
  • 145
  • 172