Search code examples
javascriptfunctioncallbackargumentsarrow-functions

creating a function in Javascript with callback arguments


I want to create "foo" function which has a callback as argument, and also wanted the callback to have two arguments as mentioned below. I tried, but didn't get a solution yet.

it doesn't have any usecase it's just a challenge for myself :)

function foo(callback){
      callback();
}
foo((arg1,arg2)=> {
      arg1=0;
      arg2=1;
});

what should i do?


Solution

  • The arguments passed to the callback are created by the function calling it, so in your case foo does that:

    function foo(callback){
          callback(/*arg1: */ 0, /* arg2: */ 1);
    }
    
    foo((arg1,arg2) => {
       console.log("arg1 is", arg1, "arg2 is", arg2);
    });

    You call a callback just like you call any other function.