It is one of the most odd behaviors I've stumbled in my JavaScript learning,
this is example:
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
var twice = multiplier(2);
console.log(twice(5));
// → 10
this is an example taken from the book Eloquent JavaScript, the author explained it in a confusing way, that makes it more odd:
In the example, multiplier returns a frozen chunk of code that gets stored in the twice variable. The last line then calls the value in this variable, causing the frozen code (return number * factor;) to be activated. It still has access to the factor variable from the multiplier call that created it, and in addition it gets access to the argument passed when unfreezing it, 5, through its number parameter.
Could anyone explain how the second call of multiplier
function in twice()
assigned the parameter to the nested function, and what if there were more nested function, what is the concept and the rule for this?