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
.