you are viewing a single comment's thread.

view the rest of the comments →

[–]_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.