-1

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?

Community
  • 1
  • 1
Old Geezer
  • 14,854
  • 31
  • 111
  • 198

2 Answers2

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

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

alert(Q(10));

Will alert 12. yis 10 as it is the value 10 which is passd as an argument and then assigned to the function parameter y. Equivalent

var y = 10; // call of Q

var x = y; call of plus2 in Q
x = x + 2;

y = x; // return of plus2

alert y; // return of Q
Axel Amthor
  • 10,980
  • 1
  • 25
  • 44
-2

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.

Old Geezer
  • 14,854
  • 31
  • 111
  • 198