How do you pass a callback function as an argument to another function in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 2 days ago

How do you pass a callback function as an argument to another function in JavaScript?

message-square
0

To pass a callback function as an argument to another function in JavaScript, pass a named function reference (without trailing parentheses ()) or a function/arrow expression into a higher-order function parameter, validate that the callback is callable (typeof callback === "function") along with other inputs (typeof / instanceof / Array.isArray), and invoke the callback safely inside a try / catch block—using a Map when dispatching or registering multiple named callbacks so dynamic keys never collide with Object.prototype properties.


1. Passing and Invoking a Callback Function Safely (typeof fn === "function")

Pass the function identifier directly (processItems(list, formatItem)) rather than calling it at the call site (processItems(list, formatItem())), validate typeof callback === "function", and wrap invocation in try / catch:

// Higher-order function that validates and invokes a callback for each element in an Array
function applyCallbackToArray(items, callbackFn, { thisArg = undefined } = {}) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an Array instance.");
  }
  if (typeof callbackFn !== "function") {
    throw new TypeError("Expected callbackFn to be a function.");
  }

  try {
    const results = [];

    for (let i = 0; i < items.length; i += 1) {
      const item = items[i];
      const transformed = callbackFn.call(thisArg, item, i, items);
      results.push(transformed);
    }

    return results;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed executing callback over array: ${message}`);
  }
}

// Example named callback function
function doubleEvenNumber(num) {
  if (typeof num !== "number" || !Number.isFinite(num)) {
    throw new TypeError("Expected num to be a finite number.");
  }
  return num % 2 === 0 ? num * 2 : num;
}

// Example usage:
// try {
//   // Pass doubleEvenNumber by reference (no parentheses)
//   const output = applyCallbackToArray([1, 2, 3, 4], doubleEvenNumber);
//   console.log("Callback results:", output); // [1, 4, 3, 8]
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Pass fn, not fn(): Passing fn() passes its return value immediately instead of passing the function itself to be called later.
  • Validate typeof callbackFn === "function" before calling: Prevents uncaught TypeError: callbackFn is not a function when optional or dynamic arguments are passed.

2. Managing Named Callbacks in a Map for Controlled Execution

When selecting which callback to pass or run based on a dynamic action key or hook name, store handlers in a Map so keys never collide with Object.prototype properties and validate every callback inside try / catch:

// Dispatch a named callback registered in a Map with strict validation and try / catch
function runRegisteredCallback(callbacksMap, actionName, payload) {
  if (!(callbacksMap instanceof Map)) {
    throw new TypeError("Expected callbacksMap to be a Map instance.");
  }
  if (typeof actionName !== "string" || actionName.trim().length === 0) {
    throw new TypeError("Expected actionName to be a non-empty string.");
  }

  const cleanAction = actionName.trim();
  const handler = callbacksMap.get(cleanAction);

  if (typeof handler !== "function") {
    throw new TypeError(`No callable callback registered for action "${cleanAction}".`);
  }

  try {
    return handler(payload);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Callback for action "${cleanAction}" threw an error: ${message}`);
  }
}

// Example usage:
// try {
//   const hooksMap = new Map([
//     ["normalizeTrim", (val) => (typeof val === "string" ? val.trim() : "")],
//     ["toUpper", (val) => (typeof val === "string" ? val.toUpperCase() : "")]
//   ]);
//   const trimmed = runRegisteredCallback(hooksMap, "normalizeTrim", "  hello world  ");
//   console.log("Result:", trimmed); // "hello world"
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Use Map rather than a plain {} object for dynamic callback names: Avoids collisions with Object.prototype properties (constructor, toString, valueOf).
  • Keep callbacks single-purpose and predictable: Avoid mutating unrelated external state unless explicitly intended.

3. this Binding, Asynchronous Callbacks, and Error Caveats

Keep these callback execution rules in mind in production JavaScript:

  • Arrow functions vs. regular functions and this: Arrow functions do not have their own this binding (they lexically capture this from surrounding scope), whereas regular functions can use .call() / .apply() / .bind() when a specific this context is required.
  • Sync vs. async callbacks: A synchronous try / catch around a callback catches synchronous exceptions, while asynchronous callbacks (setTimeout, event handlers, Promises) require their own try / catch or .catch() handling when the async turn executes.
  • Avoid deep nested callbacks (“callback hell”): Prefer clean modular functions, async / await with Promises for async flows, and clear error propagation.