DEV Community

M. Brian Dunson
M. Brian Dunson

Posted on

Help me understand this code, please

I'm working through 'Eloquent Javascript' (www.eloquentjavascript.net) and I'm not grasping how this works.

function multiplier(factor) {
  return number => number * factor;
}
let twice = multiplier(2);
console.log(twice(5));
// → 10
Enter fullscreen mode Exit fullscreen mode

I guess where I'm getting lost is how does this line worK:
let twice = multiplier(2)

In trying to understand, I did some other console.log commands to see what they would return:

console.log(multiplier(2));
// → x => x * factor
console.log(twice);
// → x => x * factor
Enter fullscreen mode Exit fullscreen mode

Can someone help me get over this mental block that I'm having? How does 'twice' have a parameter? Is 'twice' a reference to the multiplier function?

Discussion (2)

Collapse
bolt04 profile image
David Pereira • Edited on

twice has a parameter because it's a function. The reason it's a function is because the multiplier function returns a function (on that code snippet you use the lamdba function syntax). In JS this is possible because functions are first-class citizens.
Also, twice is not a reference to the multiplier function. You create a new function when you return, so it's a reference to a new function. Every time you call multiplier, you create a new function.
Hope that helped ☺

Collapse
mbdunson profile image
M. Brian Dunson Author

Ok, so what I was missing is:
return x => x * factor;

is the same as:
return function(x) { return x * factor; };

Thank you for your excellent explanation!