Full answer
In JavaScript a function is an object that can be called. Because it is a value, it can be used anywhere a value can:
- Assigned:
const greet = function () {}orconst add = (a, b) => a + b. - Stored: in an array (
[fn1, fn2]), or as an object property (a method). - Passed as an argument:
[1, 2, 3].map(double),button.addEventListener('click', handler). - Returned from a function:
makeAdder(5)returns a new function.
A higher-order function (HOF) takes a function, returns a function, or both. Built-in examples are map, filter, reduce, sort (with a comparator), forEach, setTimeout, and Promise.then. When you pass a function that will be called later, it is a callback.
Returned functions keep access to the variables where they were created, which is a closure. This makes it possible to write function factories: const multiplyBy = (n) => (x) => x * n; const double = multiplyBy(2);.
Why HOFs help: they let you separate what to do for each item from how to loop, reduce repeated code, and build reusable tools such as debounce, memoize, and retry wrappers. They also make code more declarative: users.filter(isActive).map(getName) says what you want.
Details to remember:
- Pass the function itself, not the result of calling it:
setTimeout(run, 1000), notsetTimeout(run(), 1000). The second form callsrunat once and passes its return value. - A function reference passed as a callback loses its
thisunless it is an arrow function or is bound. - Callbacks from
mapand similar methods receive(value, index, array), so passing a function that takes optional extra arguments, such asparseInt, gives surprises. - Functions have properties:
name,length(number of declared parameters), and methodscall,apply, andbind.
const add = (a, b) => a + b;
const operations = { add, subtract: (a, b) => a - b, multiply: (a, b) => a * b };
console.log(Object.entries(operations).map(([name, fn]) => `${name}(6, 3) = ${fn(6, 3)}`));
const pipeline = [(x) => x + 1, (x) => x * 2, String];
console.log(pipeline.reduce((value, fn) => fn(value), 4));
function multiplyBy(n) {
return (x) => x * n;
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log(double(21), triple(5), multiplyBy.length, double.length);
function repeat(times, action) {
for (let i = 0; i < times; i++) action(i);
}
const seen = [];
repeat(3, (i) => seen.push(i * i));
console.log(seen);
const numbers = [1, 2, 3, 4, 5, 6];
const isEven = (n) => n % 2 === 0;
const square = (n) => n * n;
console.log(numbers.filter(isEven).map(square), numbers.some(isEven), numbers.every(isEven));
console.log([5, 1, 10].sort((a, b) => a - b), ['b', 'a'].sort());
function callLater(fn, label) {
return new Promise((resolve) => setTimeout(() => resolve(`${label}: ${fn()}`), 1));
}
const run = () => 'ran later';
callLater(run, 'reference').then(console.log);
console.log('passing run() instead of run passes:', typeof run(), '(a string, not a function)');
const user = { name: 'Asha', hello() { return `hi ${this.name}`; } };
const detached = user.hello;
console.log(user.hello(), (() => { try { return detached(); } catch (e) { return e.name; } })(), detached.bind(user)());Run with Node.js v24.22.1 as js-156.js; two runs gave identical output. Output: [ 'add(6, 3) = 9', 'subtract(6, 3) = 3', 'multiply(6, 3) = 18' ] 10 42 15 1 1 [ 0, 1, 4 ] [ 4, 16, 36 ] true false [ 1, 5, 10 ] [ 'a', 'b' ] passing run() instead of run passes: string (a string, not a function) hi Asha hi undefined hi Asha reference: ran later
Key points
- First-class: functions can be assigned, stored, passed, and returned like any other value.
- A higher-order function takes or returns a function; callbacks are functions passed to be called later.
- Returned functions form closures, which makes factories like multiplyBy possible.
- Pass the function reference, not the call result; watch this and extra callback arguments.
- HOFs reduce repetition and make code declarative.
Common mistakes
- Writing setTimeout(run(), 1000), which runs the function at once.
- Passing a method as a callback and losing this.
- Passing a function with optional parameters, such as parseInt, directly to map.
- Not returning a value from the callback of map or filter.
Follow-ups
- What is the difference between a callback and a higher-order function?
- How do closures make function factories work?
- How would you write your own version of map?
Tips
- Define first-class with the four uses: assign, store, pass, return.
- Give a built-in HOF and a function factory example.
- Mention the setTimeout(run()) mistake.