CodeZettaInterview Hub

JavaScript · Functional Programming · Mid-Level · Live Coding

What is a higher-order function? Write a simple `withRetry` example.

Short Interview Answer

A function that takes functions as arguments and/or returns a function — used to abstract control flow and behavior.

Detailed Explanation

HOFs enable reusable policies: retry, debounce, authorization wrappers, middleware. They rely on closures to capture configuration. In interviews, implementing a small HOF shows API design skill. Discuss error handling, async vs sync, and preserving `this`/function names when wrapping. Too many nested HOFs can obscure stack traces — name wrappers and limit depth.

Example

function withRetry(fn, times = 3) {
  return async function retried(...args) {
    let lastError;
    for (let i = 0; i < times; i++) {
      try {
        return await fn(...args);
      } catch (err) {
        lastError = err;
      }
    }
    throw lastError;
  };
}

Interview Tip

Implement live and discuss async retry edge cases.

Common Mistake

Forgetting to return the inner function's result or rethrow the last error.

Did you know this answer?