2

I'm reading through Eloquent Javascript and saw this function:

function multiplier(factor) {
  return function(number) {
    return number * factor;
  };
}

var twice = multiplier(2);
console.log(twice(5));
// → 10

However, I'm failing to grasp how the inner function is assigning the variable (5) to the number parameter? Eloquent JS tries to explain it but I'm not getting it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
evu
  • 1,031
  • 2
  • 10
  • 29
  • 1
    After executing this line `var twice = multiplier(2);`, Twice is a function. 'twice = function(number) { return number * 2; };' And when you execute this line `console.log(twice(5));` Number will have the value 5 and it will return 10 – Gilsha Nov 06 '14 at 11:17
  • 1
    @Gilsha - Put that in an answer and you'll get my vote – myfunkyside Nov 06 '14 at 11:19
  • So if twice becomes the inner function, what happens to the factor variable? Is it stored in memory or something? This could be obvious, but not to me... – evu Nov 06 '14 at 11:21
  • Thanks @myfunkyside This question is marked as duplicate. I cant answer it. – Gilsha Nov 06 '14 at 11:25
  • Note that a javascript variable can hold a function. Factor variable will hold the parameter value passed to the multiplier function. Here it is 2. Thats how twice become a function which returns number * 2 – Gilsha Nov 06 '14 at 11:27
  • The duplicate is at the top, below the header. Although that is a very long post about closures, and while this may be a closure, I'm asking about a specific function. – evu Nov 06 '14 at 11:34

1 Answers1

1

The inner function is the return value of multiplier. It doesn't get called until console.log(twice(5)); where it is explicitly passed the value 5.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335