Course contentsShow
← JavaScript
Lesson 1226 of 2,72328. CallbacksFree lesson

Passing Arguments to Callbacks

The calling function determines what arguments are passed to your callback when invoked.

Passing Arguments to Callbacks

You'll learn how the calling function controls what data your callback receives.

The Calling Function Is in Charge

When you pass a callback to another function, you don't control when it runs or what arguments it receives. The function you're giving your callback to decides both of those things. This is a fundamental shift in control.

Think of it like giving someone your phone number. You're saying "call me," but they decide when to call and what they'll say when you pick up. You can't force them to say specific words—you just have to be ready to handle whatever they tell you.

How Arguments Flow

The calling function will invoke your callback with whatever arguments it thinks are appropriate. Your job is to write a callback that expects those arguments in the right order.

function processData(callback) {
  const result = 42;
  const status = "success";
  
  // This function decides to pass TWO arguments
  callback(result, status);
}

// Your callback must match that signature
processData(function(num, message) {
  console.log(num);      // 42
  console.log(message);  // "success"
});

The processData function determined that callbacks will receive a number first, then a string. You can't change that—you can only write your callback to accept those parameters.

Missing or Extra Arguments

If your callback expects fewer parameters, the extras are ignored. If it expects more, the missing ones are undefined:

processData(function(num) {
  // Only using first argument - "success" is ignored
  console.log(num);  // 42
});

processData(function(a, b, c) {
  console.log(c);  // undefined - only 2 args passed
});

Key Takeaway: The calling function determines what arguments your callback receives and in what order—your callback must be designed to accept whatever contract the caller defines.