0

In the code below, can someone please explain how did add5(2) get interpreted as passing an argument 2 to y argument of the inner function?

var count = 0;

function makeAdder(x) {
  return function inner(y) {
    return x + y;
  };
}
var add5 = makeAdder(5);
count += add5(2);
  • 1
    calling `makeAdder` returns a function with a bound `x` argument, called `add5`. This is later called below with it's own `y` argument and the result returned. The key point here is that calling `makeAdder` returns another function. – nicholaswmin Jun 20 '22 at 11:13

1 Answers1

0

makeAdder is what is known as a 'higher order function' - essentially a function that returns a function. Higher order functions are also functions that accept functions as parameters, so any function that takes or returns another function is a higher order function.

In this case, its returning the function named inner, although the functions can also be anonymous.

Because inner is defined in the scope of makeAdder, the value of x is captured by inner, so that it can be used later when inner is actually called.

The return value from makeAdder is assigned to add5, so add5 is now a variable holding a reference to the inner function. By adding the call operator (()) to add5 you are calling the function assigned to add5, so inner is now called with 2 as the value of y, and x is the value captured in the call to makeAdder, so 5. 5 + 2 = 7.

Dave Meehan
  • 3,133
  • 1
  • 17
  • 24