1

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?

mshwf
  • 7,009
  • 12
  • 59
  • 133

2 Answers2

0

multiplier function is returning the function inside it. So, in the first call twice will be equal to the function returned by the multiplier function like below :

twice = function(number) {
         return number * factor;
        };

Here the value of factor is 2 that is passed to the multiplier function in the first call and will be accessible in the function inside it even after the execution, this is the concept of Closures in javascript.

Second time, when you call twice(5), it returns the product of 5 which is passed to twice and factor which was passed earlier in the first call. Hence the product is 10.

Supradeep
  • 3,246
  • 1
  • 14
  • 28
0

Essentially, multiplier returns a function when it is called. Thus, when you invoke multiplier and store it in twice, a function is being stored. You can look at it this way, When you execute console.log(twice(5), it's like you're executing console.log(multiplier(2)(5))

Calvin Yee
  • 32
  • 1
  • 5