Difficulty: Intermediate
What is a higher-order function in JavaScript? Explain with practical examples, including how you would write one yourself.
A higher-order function (HOF) is a function that takes another function as an argument, returns a function, or both. JavaScript supports this because functions are first-class values: they can be stored in variables, passed around and returned like any other value. map, filter, reduce, setTimeout and addEventListener are all higher-order functions.
array.filter(isAvailable) owns the looping; you only describe the rule. The function you pass in is called a callback.createLogger('PAYMENTS') returns a logger that remembers its prefix through a closure. Middleware, debounce, memoize and React's connect style APIs all follow this shape.Many useful HOFs do both: debounce(fn, 300) takes a function and returns a new, rate-limited one.
for loop with an index, a temporary array and a push, against orders.filter(o => o.status === 'PAID').orders.filter(isPaid).map(toAmount).reduce(sum, 0).| Function | Takes | Returns |
|---|---|---|
map(fn) | transform function | new array of same length |
filter(fn) | predicate | new array of matching items |
reduce(fn, init) | reducer (acc, item) | single accumulated value |
find, some, every | predicate | item or boolean, stops early |
sort(compareFn) | comparator | the same array, sorted in place |
Function.prototype.bind | this and args | new bound function |
Since ES2023 there are non-mutating versions toSorted, toReversed and toSpliced, which pair better with functional code than the in-place sort.
['1','2','3'].map(parseInt), which returns [1, NaN, NaN] because map passes (value, index) and parseInt treats the index as a radix.setTimeout(doWork(), 1000) runs immediately.this when passing methods: button.addEventListener('click', obj.handle) calls handle with this set to the button. Use an arrow wrapper or bind.map().filter() over huge arrays in a hot path creates intermediate arrays; a single reduce or a plain loop can be cheaper when it actually matters.const orders = [
{ id: 1, status: 'PAID', amountPaise: 49900 },
{ id: 2, status: 'FAILED', amountPaise: 19900 },
{ id: 3, status: 'PAID', amountPaise: 129900 },
];
const isPaid = (o) => o.status === 'PAID';
const toAmount = (o) => o.amountPaise;
const sum = (acc, n) => acc + n;
const revenue = orders.filter(isPaid).map(toAmount).reduce(sum, 0);
console.log(`Revenue: Rs ${revenue / 100}`);
// Writing your own higher-order function: a simplified map
function myMap(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(callback(array[i], i, array));
}
return result;
}
console.log(myMap([1, 2, 3], (n) => n * 10));
// Gotcha: map passes (value, index), parseInt reads index as radix
console.log(['1', '2', '3'].map(parseInt));
console.log(['1', '2', '3'].map(Number));
filter, map and reduce each accept a callback, which is what makes them higher-order. Implementing myMap shows the callback contract (value, index, array), which also explains the parseInt surprise.
// Factory: the returned function remembers prefix via closure
function createLogger(prefix) {
return (message) => console.log(`[${prefix}] ${message}`);
}
const payLog = createLogger('PAYMENTS');
payLog('UPI collect request sent');
// Decorator: wrap any function to add timing without editing it
function withTiming(fn) {
return function (...args) {
const start = performance.now();
const result = fn.apply(this, args);
console.log(`${fn.name} took ${(performance.now() - start).toFixed(2)}ms`);
return result;
};
}
const slowSquare = (n) => { for (let i = 0; i < 1e6; i++); return n * n; };
const timedSquare = withTiming(slowSquare);
console.log(timedSquare(12));
createLogger is a factory and withTiming is a decorator; both return new functions. The timing value will differ on your machine.
Higher-Order Functions, First-Class Functions, Callbacks, Function Factories, Closures