Higher-Order Functions
Published by Brayan K
Master one of JavaScript's most powerful patterns—used everywhere from React hooks to Node.js middleware, AI pipelines, and modern framework architecture.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Separate configuration now from work later
A higher-order function accepts a function, returns a function, or does both. That describes its interface, not its timing, purity or speed. Begin by watching when a factory runs and when the function it returns runs.
function makeTagger(tag) {
console.log("configure", tag); // Runs when the factory is called.
return message => "[" + tag + "] " + message; // Runs on a later call.
}
const warn = makeTagger("WARN");
const info = makeTagger("INFO");
console.log(typeof warn);
console.log(warn("Low space"));
console.log(info("Saved"));
console.log(warn("Check input"));
// ✅ Expected output:
// configure WARN
// configure INFO
// function
// [WARN] Low space
// [INFO] Saved
// [WARN] Check inputThe returned function retains access to tag. Closures and Scope owns lexical retention; this lesson owns how to adapt function interfaces without losing arguments, receivers or return values. The factory above logs configuration, so it deliberately has an observable effect.
Taking a function does not automatically defer or repeat it
function applyTwice(fn, value) { return fn(fn(value)); }
const calls = [];
const result = applyTwice(value => { calls.push(value); return value + 3; }, 1);
console.log(result, calls.join(","));
console.log(applyTwice(value => value * 2, 2));
// ✅ Expected output:
// 7 1,4
// 8applyTwice is synchronous and calls its argument twice. A different higher-order function might never call it. Read the receiving function’s contract rather than assuming “callback” means asynchronous. Callbacks & Callback Hell owns callback execution boundaries.
function applyTwice(fn, value) { return fn(fn(value)); }
function increment(value) { return value + 1; }
console.log(applyTwice(increment(2), 0));
// ✅ Expected error:
// TypeError: fn is not a functionincrement(2) is evaluated first and supplies 3 as fn. Pass increment itself when the adapter must decide when and with which arguments to call it.
Currying and partial application change call shapes differently
const add = (a, b, c) => a + b + c;
const curriedAdd = a => b => c => a + b + c;
console.log(add(2, 3, 4));
console.log(curriedAdd(2)(3)(4));
const addTwo = curriedAdd(2);
console.log(addTwo(5)(6), addTwo(1)(1));
// ✅ Expected output:
// 9
// 9
// 13 4Currying turns this three-argument function into a chain of single-argument calls. Partial application fixes some arguments and returns a function for the remaining arguments; that returned function can still take several arguments at once.
const join = (separator, left, right) => left + separator + right;
const withDash = (left, right) => join("-", left, right);
console.log(withDash("A", "B"));
console.log(withDash("C", "D"));
// ✅ Expected output:
// A-B
// C-Dconst add = a => b => a + b;
const result = add(2, 3);
console.log(typeof result);
console.log(result(4));
console.log(add(2)(3));
// ✅ Expected output:
// function
// 6
// 5Ordinary JavaScript functions can ignore extra arguments. add(2, 3) calls only the first stage, which reads a and ignores the extra 3. A reusable library can choose to reject the wrong call shape instead; the final brief does so explicitly.
const atLeast = minimum => value => value >= minimum;
const enoughMinutes = atLeast(10);
console.log([5, 10, 12].filter(enoughMinutes).join(","));
const startsWith = prefix => text => text.startsWith(prefix);
console.log(["dev_mina", "mina", "dev_leo"].filter(startsWith("dev_")).join(","));
// ✅ Expected output:
// 10,12
// dev_mina,dev_leoThese unary predicates ignore the extra index and array arguments supplied by filter. A different function, such as parseInt passed directly to map, can interpret those extra arguments differently. map, filter & reduce owns the callback-argument examples.
A wrapper must preserve the parts of the interface it promises
const wrapWrong = fn => (...args) => { fn(...args); };
const wrapRight = fn => (...args) => fn(...args);
console.log(wrapWrong((a, b) => a + b)(2, 3));
console.log(wrapRight((a, b) => a + b)(2, 3));
// ✅ Expected output:
// undefined
// 5Forwarding arguments but forgetting return silently changes the interface. A wrapper also needs a receiver policy. An arrow wrapper has lexical this; it cannot forward the receiver chosen by a later method call.
function label(prefix) { "use strict"; return prefix + this.name; }
const wrapped = (...args) => label(...args);
const object = { name: "Mina", wrapped };
console.log(object.wrapped("Member: "));
// ✅ Expected error:
// TypeError: Cannot read properties of undefined (reading 'name')function withCallCount(fn) {
"use strict";
let calls = 0;
function wrapped(...args) {
calls++;
return fn.apply(this, args);
}
wrapped.calls = () => calls;
return wrapped;
}
const object = {
name: "Mina",
label: withCallCount(function (prefix, suffix) { return prefix + this.name + suffix; })
};
console.log(object.label("Member: ", "!"));
console.log(object.label.calls());
const other = { name: "Leo" };
console.log(object.label.call(other, "[", "]"));
console.log(object.label.calls());
function strictReceiver() { "use strict"; return this; }
console.log("plain receiver", strictReceiver() === withCallCount(strictReceiver)());
console.log("primitive receiver", strictReceiver.call(7) === withCallCount(strictReceiver).call(7));
console.log("null receiver", strictReceiver.call(null) === withCallCount(strictReceiver).call(null));
// ✅ Expected output:
// Member: Mina!
// 1
// [Leo]
// 2
// plain receiver true
// primitive receiver true
// null receiver trueStrict mode in the factory also keeps undefined, null and primitive receivers unchanged. This wrapper counts attempted synchronous calls, including calls that throw, and preserves the caller-selected receiver. It does not claim constructor compatibility or copy the original function’s properties. The this Keyword owns call/apply/bind and receiver semantics.
const original = Promise.resolve(7);
const direct = fn => (...args) => fn(...args);
const asyncWrapper = fn => async (...args) => fn(...args);
console.log(direct(() => original)() === original);
console.log(asyncWrapper(() => original)() === original);
console.log(await asyncWrapper(() => original)());
// ✅ Expected output:
// true
// false
// 7Both wrappers eventually produce the value 7, but an async function returns its own promise. Identity is part of some caching and pending-work contracts. Advanced Scope, Closures & Lexical Environments owns those shared-pending-work patterns; Mastering Promises: Chaining, Error Flow & Patterns owns promise adoption.
Function.length is metadata, not an enforced argument contract
function plain(a, b, c) {}
function defaults(a, b = 2, c) {}
function rest(a, ...others) { return others.length; }
function destructured({ value }, second) {}
console.log(plain.length, defaults.length, rest.length, destructured.length);
console.log(rest(1, 2, 3, 4));
// ✅ Expected output:
// 3 1 1 2
// 3length counts parameters before the first default, excludes a rest parameter, and counts a destructured parameter as one. It does not tell a generic curry helper how many arguments the application intends to collect. Pass an explicit arity or use an intentionally limited helper with a documented call shape.
Composition also needs an execution contract
const pipe = (...steps) => input => steps.reduce((value, step) => step(value), input);
const format = pipe(text => text.trim(), text => text.toUpperCase(), text => "[" + text + "]");
console.log(format(" Mina "));
console.log(pipe()(7));
console.log(pipe(value => value + 2, value => value * 3)(4));
console.log(pipe(value => value * 3, value => value + 2)(4));
// ✅ Expected output:
// [MINA]
// 7
// 18
// 14This small helper is synchronous and unary; it does not await a promise, validate stage types or preserve method receivers. An empty pipe is the identity function. Functional Programming in JavaScript owns stage ordering and input/output contracts; Async/Await Architecture & Best Practices owns asynchronous workflow policy.
Guided exercise: prepare a reusable two-stage predicate
Fill the literal hints to return a checker and require every configured check to pass. The configuration is created once, while each string is checked later.
const minLength = minimum => ___ => value.length >= minimum; // 👉 replace ___ with value
const startsWith = prefix => value => value.___(prefix); // 👉 replace ___ with startsWith
const all = checks => value => checks.___(check => check(value)); // 👉 replace ___ with every
const valid = all([minLength(5), startsWith("dev_")]);
console.log(valid("dev_mina"), valid("dev_"), valid("admin_mina"));
// ✅ Expected output:
// true false falseIndependent brief: curry exactly three arguments without shared partial state
Write curry3(fn) for functions that do not depend on this. Reject a non-function immediately with TypeError("fn must be a function"). Return three stages; each stage requires exactly one supplied argument, including undefined as a valid supplied value, otherwise throw TypeError("each stage requires one argument"). Invoke fn only after the third stage, passing all three collected values in order.
Reusing an earlier partial stage must not mix arguments between branches. Preserve the exact returned object or promise and propagate the exact thrown error. Check delayed invocation, two branches from one partial, explicit undefined, too few/many arguments, result identity and failure identity. This helper is not a general curry implementation or a constructor wrapper.
function curry3(fn) {
if (typeof fn !== "function") throw new TypeError("fn must be a function");
function stage(collected) {
return function (value) {
if (arguments.length !== 1) throw new TypeError("each stage requires one argument");
const next = [...collected, value];
return next.length === 3 ? fn(...next) : stage(next);
};
}
return stage([]);
}
let calls = 0;
const format = curry3((a, b, c) => { calls++; return [a, b, c].join(":"); });
const first = format("A");
const left = first("B");
const right = first("C");
console.log("before final", calls);
console.log(left("D"), right("E"), calls);
console.log(first("F")("G"), calls);
console.log(curry3((a, b, c) => [a, b, c].map(String).join(","))(undefined)(0)(false));
const object = { ready: true };
console.log(curry3(() => object)(1)(2)(3) === object);
const promise = Promise.resolve(7);
console.log(curry3(() => promise)(1)(2)(3) === promise);
const reason = new Error("original failure");
try { curry3(() => { throw reason; })(1)(2)(3); }
catch (error) { console.log(error === reason); }
for (const invalid of [() => format(), () => format(1, 2), () => first(), () => left(1, 2), () => curry3(null)]) {
try { invalid(); } catch (error) { console.log(error.name, error.message); }
}
// ✅ Expected output:
// before final 0
// A:B:D A:C:E 2
// A:F:G 3
// undefined,0,false
// true
// true
// true
// TypeError each stage requires one argument
// TypeError each stage requires one argument
// TypeError each stage requires one argument
// TypeError each stage requires one argument
// TypeError fn must be a functionReference notes
The Function.length reference defines its metadata rules. The apply reference explains receiver and argument forwarding. The checked wrappers above state their own narrower contracts; they do not claim to reproduce every behaviour of built-in bind.
Practice quiz
What does this complete program print? const add=a=>b=>a+b; console.log(add(2)(5));
- 7
- undefined
- function
- 25
Answer: 7. The first call retains 2 and the second supplies 5.
What does this complete program print? const add=a=>b=>a+b; console.log(typeof add(2,5));
- number
- function
- undefined
- object
Answer: function. Only the first unary stage is invoked; the extra argument is ignored.
What does this complete program print? const wrap=fn=>(...args)=>{fn(...args)}; console.log(wrap((a,b)=>a+b)(2,3));
- 5
- NaN
- undefined
- TypeError
Answer: undefined. The wrapper discards the return value.
What does this complete program print? function fn(a,b=2,c){} console.log(fn.length);
- 3
- 2
- 0
- 1
Answer: 1. Only parameters before the first default contribute to length.
What does this complete program print? function fn(a,...rest){return rest.length} console.log(fn.length,fn(1,2,3));
- 1 2
- 3 2
- 1 3
- 2 2
Answer: 1 2. The rest parameter does not contribute to length but still receives extra arguments.
What does this complete program print? const configured=prefix=>text=>prefix+text; const tag=configured("A:"); console.log(tag("one"),tag("two"));
- one two
- A:one A:two
- A:one two
- one A:two
Answer: A:one A:two. The same partial function retains the prefix for both later calls.
What does this complete program print? const p=Promise.resolve(3); const wrap=fn=>async()=>fn(); console.log(wrap(()=>p)()===p);
- true
- 3
- false
- undefined
Answer: false. An async wrapper returns a distinct adopting promise.
What does this complete program print? const pipe=(...steps)=>input=>steps.reduce((value,step)=>step(value),input); console.log(pipe()(4));
- undefined
- TypeError
- 0
- 4
Answer: 4. With no stages, the initial input is returned unchanged.
Continue this course
- Previous: Functional Programming in JavaScript
- Next: Pure Functions, Immutability & Side Effects — Write predictable code by controlling side effects and avoiding mutation
- Quick reference: JavaScript cheat sheet