0

I am reading about closures right now and am confused by this javascript code.

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

How does the console.log work? Since add5 = makeAdder(5), then isn't add5(2)) = makeAdder(5)(2)?

I am wondering how y = 2 is determined by javascript in this function, as the function only defines one argument x.

EDIT: Sorry to make it clear, what I was confused about was the fact that it appears like 5 and 2 are both being passed into makeAdder(x).

Shawn123
  • 437
  • 2
  • 5
  • 15
  • `makeAdder` sets the value of `x` and returns the anonymous function. `add5` == `function (y) { return 5 + y };` – bcr Sep 29 '15 at 13:51
  • Similar http://stackoverflow.com/questions/32753388/can-someone-explain-to-me-how-this-function-works/32753411#32753411. This might help you – Tushar Sep 29 '15 at 13:52
  • makeAdder() returns a function that expects a single value, y. makeAdder() is a closure around the function it returns, and it holds the value for x. Not sure exactly what you're trying to ask... – lintmouse Sep 29 '15 at 13:52
  • 1
    Log `add5` (without parentheses) before your current loggings, you'll understand where `2` is passed. – Teemu Sep 29 '15 at 13:52
  • See also [Make this syntax possible: var a = add(2)(3); //5](http://stackoverflow.com/q/2272902/1048572) – Bergi Sep 29 '15 at 14:29

0 Answers0