multiplier accept a number and returns a function
the function returned for multiplier(2) is number => number * 2
this function is stored in twice and when you call twice(5), the number 5 is passed in the number parameter so it returns 10
function multiplier(factor) {
// return a function...
// this function takes a number and
// multiplies by factor (a value in the enclosing scope, closure, of the multiplier function
return function(number) { return number * factor }
}
const multiplyBy2 = multiplier(2)
/*
under the hood multiplyBy2 looks like this.
multiplyBy2(number){
return number * 2; // factor (is a variable in the closure its value is 2)
}
*/
const multiplyBy11 = multiplier(11)
/*
under the hood multiplyBy11 looks like this.
multiplyBy2(number){
return number * 11; // factor (is a variable in the closure its value is 11)
}
*/
console.log(multiplyBy2(10)); // 20
console.log(multiplyBy11(8)); // 88
Javascript creates those functions and when it is time to run them it will evaluate ‘factor’ to the value that
is in closure (the local enclosing scope)
I’m still a little confused though. Following the “under the hood” explanations, what happens under the hood at this stage: console.log(multiplyBy2(10));
This is what I understand happens under the hood:
multiplyBy2 returns number * 2
So then we have console.log((number*2)(10))…?
How does that become console.log(10 * 2)…?
I guess I don’t get how 10 becomes the number parm…?
You’re getting really close. I think maybe the thing that’s tripping you up is not understanding that functions can be assigned to variables in JavaScript.
Using @milesmeow 's code, the function multiplier returns a function. The line const multiplyBy2 = multiplier(2) is assigning the function returned from multiplier to the variable named multiplyBy2.
We can now call multiplyBy2 just like any other function, by using (). It also takes one argument, in this case we called it number. So the line multiplyBy2(10), is calling the function multiplyBy2 with the argument number as the value 10.
So the second step you wrote
So then we have console.log(number(10))
should instead be console.log(multiplyBy2(10)) which evaluates down to console.log(10 * 2).
You use it constantly when programming JavaScript, you just tend not to notice it because large chunks the way the language works are built upon it so it’s just How Things Work (for example all async stuff and anything that uses callbacks). Most of the examples, like the one that threw OP, are abstract and imo maybe actively make it seem more esoteric and complicated than it actually is. I would say most transparently they are used where objects (class instances) would be used in an OO language (though probably less true since ES2015 and modules & class syntax)