Sub topic 19
Returning Functions
This chapter assumes you know how to declare and call functions, how default parameter values work, and how arrow functions return an expression implicitly. Those topics come from earlier chapters. Here the focus is on a function whose return value is another function.
Functions Are Values
In JavaScript, a function is a value, just like a number or an object. You can store it in a variable, pass it as an argument, and return it from another function. When a function returns a function, the caller gets something it can call later.
function makeMultiplier(factor = 2) {
return (n) => n * factor;
}
const triple = makeMultiplier(3);
console.log(triple(5)); // 15
console.log(makeMultiplier()(5)); // 10makeMultiplier(3) runs once and returns an arrow function. That arrow function is stored in triple. Calling triple(5) runs the inner function. The second line calls both functions in one expression. makeMultiplier() uses the default factor of 2 and returns a function, and (5) calls that function right away.
Closures: Remembering the Outer Parameters
By the time triple(5) runs, makeMultiplier has already returned. Its parameter factor still exists, though, because the inner function refers to it. A function that keeps access to variables from the scope where it was created is called a closure.
The inner function does not hold a copy of factor. It holds a reference to the environment, meaning the set of variables, that existed during that call to makeMultiplier. Each call creates a new environment, so each returned function has its own factor.
function makeMultiplier(factor = 2) {
return (n) => n * factor;
}
const triple = makeMultiplier(3);
const tenTimes = makeMultiplier(10);
console.log(triple(4)); // 12
console.log(tenTimes(4)); // 40
console.log(triple === tenTimes); // false: two distinct function objectsClosures Capture Variables, Not Snapshots
A closure sees the current value of a variable at the moment it runs, not the value at the moment it was created. This is how private state works: the outer function declares a variable, and the returned functions read and update it.
function makeCounter(start = 0) {
let count = start;
return {
increment: () => ++count,
current: () => count,
};
}
const counter = makeCounter(5);
counter.increment();
counter.increment();
console.log(counter.current()); // 7
console.log(counter.count); // undefined: count is not a propertyBoth functions in the returned object share one count variable because they were created during the same call. Code outside has no way to reach count except through these functions. This example also returns several functions at once by putting them in an object, the same technique used for returning multiple values.
Arrow Chains and Partial Application
Arrow functions with implicit returns make it short to write a function that returns a function. Each => adds one level.
const add = (a) => (b) => a + b;
const addTen = add(10);
console.log(addTen(5)); // 15
console.log(add(1)(2)); // 3Read add from left to right. It takes a and returns a function that takes b and returns a + b. When you fix some arguments now and supply the rest later, that is called partial application. It lets you build specialized functions from general ones and pass them to array methods:
const add = (a) => (b) => a + b;
const prices = [10, 20, 30];
console.log(prices.map(add(5))); // [15, 25, 35]add(5) is evaluated once and returns a one-parameter function, which map calls for each element.
Returning a Configured Function
A common real-world use is a factory that validates its configuration once and returns a function that is cheap to call many times.
function makeFormatter({ currency = "USD", locale = "en-US" } = {}) {
const formatter = new Intl.NumberFormat(locale, {
style: "currency",
currency,
});
return (amount) => formatter.format(amount);
}
const formatEuro = makeFormatter({ currency: "EUR", locale: "de-DE" });
const formatDefault = makeFormatter();
console.log(formatEuro(1234.5)); // "1.234,50 €"
console.log(formatDefault(1234.5)); // "$1,234.50"The Intl.NumberFormat object is built once per factory call, not once per formatted number. The options object uses destructuring with defaults, so callers can leave out any setting.
Common Errors
Forgetting to Call the Returned Function
A missing set of parentheses gives you the function itself where you wanted its result.
function makeMultiplier(factor = 2) {
return (n) => n * factor;
}
const result = makeMultiplier(3);
console.log(typeof result); // "function", not a number
console.log(result(5)); // 15If you see [Function] or function where you expected data, check whether a call is missing.
Calling Too Early
The opposite mistake happens when an API wants a function and you pass the result of calling one.
function makeGreeter(name) {
return () => console.log(`Hello, ${name}`);
}
// Wrong: makeGreeter("Ana")() runs now and passes undefined to setTimeout
// setTimeout(makeGreeter("Ana")(), 1000);
// Right: pass the returned function
setTimeout(makeGreeter("Ana"), 1000); // logs "Hello, Ana" after one secondSharing a Variable by Accident
Closures created in a loop share whatever variable they capture. With var, the whole loop has one variable, so every function sees its final value. With let, each iteration gets a new binding.
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map((f) => f())); // [3, 3, 3]
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map((f) => f())); // [0, 1, 2]Keeping Large Data Alive
A returned function keeps its environment in memory as long as the function itself is reachable. If the outer function holds a large array that the inner function doesn't need, avoid referring to it from the inner function, or extract only the value you need before returning.
function makeSizeReporter(bigArray) {
const size = bigArray.length; // keep only what is needed
return () => `Size: ${size}`;
}
const report = makeSizeReporter(new Array(1_000_000).fill(0));
console.log(report()); // "Size: 1000000"Engines usually keep only the variables an inner function actually uses, but this behavior is an optimization, not a guarantee. Copying the needed value into a small variable makes your intent explicit.
When to Return a Function
| Situation | Returning a function helps because |
|---|---|
| Same operation with different fixed settings | Each factory call bakes in its settings |
| Callbacks for `map`, `filter`, event handlers | You can produce a correctly shaped one-parameter function |
| Private state | Variables in the outer scope can't be reached from outside |
| Expensive setup, cheap repeated use | Setup runs once per factory call |
If the function will only be called once with all its arguments known, a plain function with several parameters is simpler.
Exercise
What does this code log, and why? function makeAdder(x) { return (y) => x + y; } const a = makeAdder(2); const b = makeAdder(2); console.log(a(3), a === b);
Show answer
It logs 5 false. a(3) adds the captured x of 2 to 3. Each call to makeAdder creates a new function object with its own environment, so a and b are different functions even though they behave the same way.
Exercise
Write a function once(fn) that returns a new function. The first call to the new function calls fn with the given arguments and returns its result. Later calls return that first result without calling fn again.
Show answer
function once(fn) { let called = false; let result; return (...args) => { if (!called) { called = true; result = fn(...args); } return result; }; }. The variables called and result live in the closure, so they persist between calls. The rest parameter and spread pass any arguments through to fn.
Exercise
Given const counter = makeCounter(0); from this chapter, a teammate writes const inc = counter.increment(); inc(); and gets a TypeError. What went wrong?
Show answer
counter.increment() calls the function and returns a number (1), so inc is a number, and calling a number throws a TypeError. They meant const inc = counter.increment; to store the function itself, then inc() to call it.