JavaScript - Why this multiplier closure function works? [duplicate]

2 weeks ago 14
ARTICLE AD BOX

I´m following the "Eloquent JavaScript" 4th edition book, and there is the following chunk of code:

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

I read about Closure Functions, and what I understand is that Closure Functions have access to their own lexical environment (local variables and parameters) as well as their parents' lexical environment. Everything is OK with this.

However, what I don´t understand about the previous function is why it is working.

I mean, when invoking multiplier( 2 ), I suppose "factor" acquires the value of 2 ( but "number" is undefined, right ? ), and the complete multiplier function returns a "dash function" :

number => number * factor;

This last is assigned to "twice" ("twice" is similar to a pointer to a function structure, am I correct?).

Later, in console.log(twice(5));, I am calling "twice" with 5 as an argument, so I am assuming again that 5 will update "factor", not "number".

So what I'm not seeing is why in the call, 5 updates "number" and not "factor", because the output is 10.

I will appreciate any clarification or correction on my assumptions.

Read Entire Article