Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a function Chrome Dev tools

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);
like image 581
John Coolidge Avatar asked Dec 21 '15 17:12

John Coolidge


2 Answers

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".

like image 103
apsillers Avatar answered Sep 22 '22 00:09

apsillers


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.

like image 44
Josh Beam Avatar answered Sep 20 '22 00:09

Josh Beam