-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?

4
  • because it is same as function Q(y) {...} Commented Sep 19, 2015 at 16:54
  • I get 12: jsfiddle.net/4ce9nch0 Commented Sep 19, 2015 at 16:55
  • Would you question y being 10 with: var Q = function(y) { alert(y); } Q(10);? Commented Sep 19, 2015 at 16:57
  • @AdrianLynch Yes I still would, because of my usual understanding of the meaning of the = sign and my poor understanding of functions as first class objects. I replaced the anonymous function with a named function and it became clearer. Commented Sep 19, 2015 at 17:05

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.