This code is a good demonstration of JavaScript's closures.
When you run:
var multiplyBy3 = makeMultiplier(3);
makeMultiplier
is called, which creates a local variable myFunc
, whose value is a JavaScript function. myFunc
's body references multiplier
, which comes from the parameter to makeMultiplier(multiplier)
, and x
, which comes from the function's own parameter x
.
makeMultiplier
then returns myFunc
, which is now a closure since the variable in scope when it was created, namely multiplier
, is still intact, even though makeMultiplier
itself has exited.
Now, since the return value of makeMultiplier(3)
was a function, multiplyBy3
now has that function as its value. As such, you can now call multiplyBy3
as a regular function, which is what happens in the next line.
console.log(multiplyBy3(10));
This line logs the return value of multiplyBy3
, which was multiplier * x
.
x
was just passed in to the function as its only parameter, so x
is 10
.
multiplier
is the same as the multiplier
from the previous call to makeMultiplier
, so multiplier
is 3
.
Thus, multiplyBy3
returns 3 * 10
, which is 30
, which is the output that you see logged in your browser's console.