JavaScript · Lesson 8 of 20 · 3 min
Higher-Order Functions & Callbacks
This is how you demonstrate a core JavaScript competency: treating functions as values. Master this to explain decorators, middleware, and the composition patterns used in modern frameworks.
The core pattern: Separating 'what' from 'how'
A higher-order function (HOF) is a function that takes another function as an argument, returns a function, or both. The function passed as an argument is called a callback.
That's it. There's no magic.
Think of Array.prototype.map. It’s a HOF. It provides the "how": it iterates over an array, calls a function for each item, and builds a new array from the results. You provide the "what" via the callback function, which defines the transformation logic for a single item. This separation makes map a reusable piece of machinery and your transformation logic a pluggable component.
This pattern is everywhere: setTimeout takes a callback to run later, addEventListener takes a callback to run on an event, and array methods like filter and reduce take callbacks to define their logic.
How to talk about data transformation
In an interview, you will be asked to manipulate data. Chaining HOFs is the declarative, readable way to do it. Contrast this with a single, monolithic for loop filled with if statements.
For example, to get the names of all in-stock products costing less than $100:
const cheapInStockProducts = products
.filter(product => product.inStock && product.price < 100)
.map(product => product.name);
This is self-documenting. It reads "filter the products, then map the results to their names." An imperative loop forces the reader to mentally execute the code to understand its purpose.
The interview angle: When given a data transformation task, start with a chain of HOFs. It shows you value clarity and composition. You can always discuss performance trade-offs later if the interviewer pushes, but declarative code is the right default.
When to write your own HOF: The decorator pattern
HOFs aren't just for arrays. They are a primary tool for augmenting or changing a function's behavior without modifying the function itself. This is the decorator pattern.
Imagine you need to log how long a function takes to run. You could add logging code to every function, or you could write one HOF to do it for you.
function withExecutionTimeLogger(func) {
// This HOF returns a new function that "wraps" the original.
return function(...args) {
console.log(`Executing '${func.name}'...`);
const start = performance.now();
const result = func(...args);
const end = performance.now();
console.log(`'${func.name}' finished in ${end - start} ms.`);
return result;
};
}
function processData(data) {
// Original business logic, untouched.
return data.map(item => item * 2);
}
// Create the decorated function.
const loggedProcessData = withExecutionTimeLogger(processData);
// Use the new function.
const result = loggedProcessData([1, 2, 3]); // Logs execution time
This keeps your business logic clean. The processData function only worries about processing data, not about logging.
In an interview, calling this a "decorator pattern" signals a deeper understanding of software design principles. It's a way to implement cross-cutting concerns like logging, caching, or authentication.
The classic trap: Losing this in callbacks
This is a critical interview checkpoint. When you pass a method of a class or object as a callback, its connection to this can be broken.
The trap: A candidate writes code like this, and this.name is undefined inside the setTimeout callback.
class DataFetcher {
constructor() {
this.name = "DataFetcher";
}
fetch() {
console.log(`${this.name} is fetching...`);
// Problem: `this` inside the callback is not the DataFetcher instance.
// In non-strict mode it's `window`, in strict mode it's `undefined`.
setTimeout(function() {
console.log(`Data received by ${this.name}`); // Fails
}, 1000);
}
}
const fetcher = new DataFetcher();
fetcher.fetch();
The function() {} callback creates its own this context, which is not the class instance. There are two primary solutions.
-
Arrow Functions (Modern solution): Arrow functions do not have their own
this. They inherit it from their parent (lexical) scope. This is almost always what you want.// Inside the fetch method: setTimeout(() => { console.log(`Data received by ${this.name}`); // Works }, 1000); -
.bind(this)(Older solution): You can explicitly bind thethiscontext to the function. It's important to know this exists, but preferring arrow functions shows you're current.// Inside the fetch method: setTimeout(this.handleResponse.bind(this), 1000); // ... handleResponse() { console.log(`Data received by ${this.name}`); // Works }
Be ready to explain why the arrow function works. It closes over the this from its surrounding environment.
Try it
Implement a debounce function. It's a HOF that takes a function and a delay in milliseconds. It should return a new, debounced function that only executes the original function after the specified delay has passed without any new calls. This is a common interview problem that tests your understanding of HOFs, callbacks, and closures.
Next: We'll see how HOFs that return functions create closures, a powerful tool for managing state, in Scope and Closures.
Lock it in — apply this lesson under interview conditions.