1

I have the following code from a javascript book and the callback seems to be passed an expression as an argument. Is that the case or am I seeing this wrong? I didnt know, even though it works, that that was possible.

function multiplybytwo(a,b,c,callback)  {
  var i, ar =[];
  for(i=0;i<3;i++)  
  {
    ar[i] = callback(arguments[i]*2);  
  }
  return ar;  
}  

function addone(a)  {
  return a+1;  
} 

myarr =multiplybytwo(1,2,3,addone);
2
  • 1
    No, you're not seeing this wrong, you can pass functions to other functions as arguments. (I suggest you grab a lambda calculus book if this seems weird.) Commented Dec 17, 2012 at 0:12
  • 2
    Calling a function and passing an expression as an argument is pretty standard in every language that I'd care to use - it's not just a JS thing. The expression is evaluated and the resulting value is passed to the function. Note that even something simple like someFunc(1) is passing an expression to a function, it's just that the expression is a simple number, 1 - but you can put pretty much any expression, including things that call other functions, e.g., someFunc(someOtherFunc(x*2) / 7 + (aThirdFunc() ? 1 : -1)) Commented Dec 17, 2012 at 0:13

3 Answers 3

1
callback(arguments[i]*2); 

is equivalent to

var a = arguments[i]*2;
callback(a);

Same as callback(1+2); to callback(3);

Sign up to request clarification or add additional context in comments.

Comments

0

The callback is passed the result of that expression.

Comments

0

Arguments are evaluated before they are passed to functions.

function foo( a ) {
    alert( a );
}

function bar( ) {
    return 1;
}

foo( bar( ) );

The above (demo) will display 1.

Comments

Your Answer

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