Reputation: 155
This question may be answered elsewhere but I wasn't even sure how to begin searching for the answer. I'm new to JavaScript so this one is a struggle for me to understand.
Given the following code:
function multiple(n) {
function f(x) {
return x * n;
}
return f;
}
var triple = multiple(3);
var quadruple = multiple(4);
When I pass the following into the console:
console.log(triple(5));
I get what I expect, that is, 15. Likewise with any number, it will be tripled (or quadrupled if I used the second function).
But when I type triple into the console I get the following code:
f(x) {
return x * n;
}
Shouldn't the console return...
f(x) {
return x * 3;
}
...since 3 is coded into the function by virtue of the following code:
var triple = multiple(3);
Upvotes: 6
Views: 126
Reputation: 28157
Well, it is the same as it would if you had:
var n = 3;
function f(x) {
return n * x;
}
If you log f
you will see the function above, but when you call it n
will get its value from the closest variable called n
in the scope chain, in our case n = 3
, the value for the n
declared in the global scope.
I don't know the exact way in which the JS
engine stores the n
variable inside that closure (in your case the closure created by the multiple
function), but what is the important thing is that variables inside a closure are saved by reference
not by value.
Upvotes: 2
Reputation: 115980
3
is not hard-coded into the function. The code of f
refers to the variable n
, not the number 3
. In your code, it so happens that there is no way to modify n
, but imagine some code where there is a way to modify n
:
function multiple(n) {
function f(x) {
return x * n;
}
function modifyN(newN) {
n = newN;
}
return { f: f, modifyN: modifyN };
}
var resultFor3 = multiple(3);
var triple = resultFor3.f;
var modifyTripleN = resultFor3.modifyN;
As you can see n
is not hard-coded; it's no different from any other variable. In your specific example there is no way to modify n
after the termination of multiple
, but that does not make the values inside of the closure created by the invocation of multiple
in any way "hard-coded".
Upvotes: 3
Reputation: 19792
Typing triple
simply shows the source code of your function.
since 3 is coded into the function by virtue of the following code
That is an incorrect statement. You're not changing the source code of the function. To change the source code, you would have to redefine the entire function. All you're doing is passing in a parameter. The console is giving you the correct output.
When you're passing in a parameter to a function, on a high-level, at runtime it's just looking for whatever value is stored at the memory address for that variable (or something like that). But it is not rewriting the source code of the function.
Upvotes: 2