Javascript functions question

I copied this from the Eloquent Javascript book topic functions and closure (page 48). I don’t understand how the number variable gets it’s value assigned. Can anyone explain? Thx.

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

Explanation from the book:
The explicit local binding from the wrapValue example isn’t really needed
since a parameter is itself a local binding.
Thinking about programs like this takes some practice. A good mental model
is to think of function values as containing both the code in their body and the
environment in which they are created. When called, the function body sees
the environment in which it was created, not the environment in which it is
called.
In the example, multiplier is called and creates an environment in which its
factor parameter is bound to 2. The function value it returns, which is stored
in twice, remembers this environment. So when that is called, it multiplies its
argument by 2.

2 Likes

Greetings @Bossman,

Well, one point to always keep in mind, whenever you see a “=>” , it means it is a nameless function.
So, behind the scenes this is what really happens –

function multiplier(factor) {           //outer enclosing function
    return function (number) {        //inner function that gets returned upon calling the outer function
               return number * factor};
              }
  }
let twice = multiplier(2); //here "twice" gets assigned the inner function. and the argument "2" gets assigned to the "factor" variable
console.log(twice(5)); // you call the inner function by passing a argument which gets stored in the "number" variable

Hope this makes sense and clears it out for you. ES6 syntax is pretty complex at first with all the implicit function calls and bindings but it helps to visualize it in the non ES6 syntax at first until you get a hang of it.

Happy Learning! :smiley:

2 Likes

@Malik oh wow and of course… functions are value too :open_mouth:. Thank you so much for this answer!!! Yes I get it now. That’s so powerful. And thank you for rewriting this in an easier to understand format. You have no idea how happy I am right now. :pray: :pray: :pray: I feel like I discovered a new quantum particle of some sort lol.

1 Like

Haha glad I could clear it out for you. :smile:

If you have any further questions, we are always here to help.

Cheers !

1 Like