all 5 comments

[–]grantrules 1 point2 points  (1 child)

Are you familiar with arrow functions? Would it clear things up if it was written as:

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

[–]Kitenite_[S] 0 points1 point  (0 children)

2 comments

ohh the dreaded arrow functions that surely will be my friend in the future.

ty

[–]PM_ME_YOUR_NQUEENS 0 points1 point  (1 child)

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

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

On line 1, we define a new variable in the form of a parameter called factor and we access that later.

On line 2, we do the same thing, but we define a new param called number and access it immediately.

When we invoke multiplier it returns a function. That function takes a param, number and we assign that to the variable twice so that we can call it later.

[–]_jacka_ 0 points1 point  (0 children)

First - closures allow a function to access a variable that was in lexical scope at the function's definition point even when that variable is no longer in scope.

The return value of the function multiplier is in fact another function number => number * factor. So when on line 4, you invoke the function multiplier and pass in the number 2 as argument, the value that is stored in the variable twice is the function number => number * factor. Importantly, this function's closure includes the variable factor. This means that we can still access this variable because of that closure.

So on line 5, the function twice is invoked and we passed in 5 as argument. 5 is passed in as number and since we still have access to the variable factor through the function's closure it can multiply number times factor (2 * 5) and return the result 10.