Search code examples
javascriptfirst-class-functions

Parameters of a function variable


After distilling the answers to How are parameters handled when passing functions in Javascript? I ended up with one question I need to clarify.

In the sample below:

function plus2(x) { return x+2; }

var Q = function(y) { return plus2(y); }

alert(Q(10));

Why does the invocation of Q with an argument of 10 result in y getting the value 10?


Solution

  • Replacing the anonymous function with a named function gave me a little bit more clarity:

    function plus2(x) { return x+2; }
    function dummy(y) { return plus2(y); }
    
    var Q = dummy;
    
    alert(Q(10));
    

    Q then becomes a sort of alias for dummy.