javascriptcallbackparameter-passing

JavaScript: Passing parameters to a callback function


I'm trying to pass parameters to a function used as callback. How can I do that?

This is my try:

function tryMe(param1, param2) {
  alert(param1 + " and " + param2);
}

function callbackTester(callback, param1, param2) {
  callback(param1, param2);
}

callbackTester(tryMe, "hello", "goodbye");


Solution

  • If you want something slightly more general, you can use the arguments variable like so:

    function tryMe(param1, param2) {
      alert(param1 + " and " + param2);
    }
    
    function callbackTester(callback) {
      callback(arguments[1], arguments[2]);
    }
    
    callbackTester(tryMe, "hello", "goodbye");

    But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)