function makeIncreaseByFunction(increaseByAmount) {
return function (numberToIncrease) {
return numberToIncrease + increaseByAmount;
};
}
makeIncreaseByFunc
With intermediate variable:
var increaseBy3 = makeIncreaseByFunction(3);
var foo = increaseBy3(10);
Without intermediate variable:
var foo = makeIncreaseByFunction(3)(10);
In both cases, the first invokation passes the argument 3
to makeIncreaseByFunction
, and as a result it returns the inner function that has closed over increaseByAmount
with the value of 3
. Whether you create a variable for the intermediate function returned by makeIncreaseByFunction
, or just invoke it directly, it does the same thing.
Can you explain a little bit more detail about how in var foo = makeIncreaseByFunction(3)(10); the 10 is getting to the inner function? It just looks syntactically different from how arguments usually get passed in Javascript to me. – ggg
makeIncreaseByFunction(3)
returns a function, specifically the "inner function" defined inside makeIncreaseByFunction
. As will all functions, you call it with the function ( arguments )
syntax. You can write it like this if it makes more sense to you this way:
( makeIncreaseByFunction(3) )(10)
What happens here is makeIncreaseByFunction(3)
gets called first and returns the ⟪inner function⟫, and then we call ⟪inner function⟫(10)
.
If you were evaluating this by hand (I think this is what you meant by "syntactically"), you could think of it happening step-by-step like this:
// Original invocation
var foo = makeIncreaseByFunction(3)(10);
// Substitute the definition of makeIncreaseByFunction
var foo = (function (increaseByAmount) {
return function (numberToIncrease) {
return numberToIncrease + increaseByAmount;
};
})(3)(10);
// Apply the parameter 3
var foo = (function (numberToIncrease) {
return numberToIncrease + 3;
})(10);
// Apply the parameter 10
var foo = 10 + 3;
// Final result
var foo = 13;
Note: If you want to be technical, all we're doing here is two Beta reductions—but unless you have background with the Lambda Calculus that will probably confuse you more than it will help you!