In the Flatiron lesson I'm doing on closures, there is the following example:
function retailPriceMaker(manufacturePrice) {
return function(marketMultiplier) {
return marketMultiplier * manufacturePrice;
};
}
const retailPriceForNine = retailPriceMaker(9);
retailPriceForNine(2);
// 18
The lesson of course talks about how when the function inside retailPriceMaker
is declared, the closure has access to (closure over) the variables in its scope, i.e., manufacturePrice
, and retains it even when it's called, later.
I do understand this, as much as it makes my brain hurt.
One way that makes it a lot simpler for me is to think of it this way:
retailPriceMaker(9)
returns the following function:
function(marketMultiplier) {
return marketMultiplier * 9;
};
Where the fact that there was ever a variable called manufacturePrice
does not matter and might as well be erased from the returned function's history books.
The idea that a closure "writes in" the values that are passed to it, rather than thinking of the variables/arguments being referenced in seeming absentia, is a LOT easier to wrap my head around.
So my question is: is this a valid way to think of closures, or am I missing something? It does seem a little too simple, and I would assume that if my explanation were completely valid:
- Closures would indeed be taught this way
- The JavaScript console would show the "filled in" function when you call the returned function:
function retailPriceMaker(manufacturePrice) {
return function(marketMultiplier) {
return marketMultiplier * manufacturePrice;
};
}
const retailPriceForNine = retailPriceMaker(9);
retailPriceForNine;
// ƒ (marketMultiplier) {
// return marketMultiplier * 9;
// }
So, what, if anything, am I missing? Or have I just turned everyone's world upside down? (highly, completely unlikely)