Sub topic 11
How Defaults and Rest Affect function.length
Every JavaScript function has a length property. It tells you how many arguments the function "expects". That sounds simple. Once a parameter list includes default values or a rest parameter, though, the number often differs from what you see in the source. This chapter covers the exact counting rule, the code that depends on it, and the bugs that come from it.
This chapter assumes you already know how to declare default parameters, rest parameters, and destructured parameters, and that you know the difference between parameters and arguments. Earlier chapters cover all of these.
The Counting Rule
function.length counts the parameters that come before the first parameter that has a default value or is a rest parameter. Counting stops at that point. Every parameter after it is ignored, including plain ones that have no default.
function f(a, b = 2, c) {}
function g(a, ...rest) {}
console.log(f.length); // 1
console.log(g.length); // 1In f, the parameter c has no default, but it comes after b = 2, so it is not counted. In g, the rest parameter is never counted.
The rule is positional. It does not sum up the parameters that lack defaults. It stops at the first parameter that is "optional" in its syntax.
Reference Table
Destructured parameters follow the same rule. A destructuring pattern counts as one parameter. If the whole pattern has a default, such as = {}, it stops the count like any other default. Defaults inside the pattern do not matter.
| Signature | `length` | Why |
|---|---|---|
| `function (a, b, c)` | 3 | No defaults, no rest |
| `function (a, b = 1)` | 1 | Stops at `b` |
| `function (a = 1, b, c)` | 0 | Stops at the first parameter |
| `function (a, b = 1, c)` | 1 | `c` comes after a default |
| `function (...args)` | 0 | Rest is never counted |
| `function (a, b, ...rest)` | 2 | Rest is never counted |
| `function ({ x, y = 5 })` | 1 | Inner defaults do not count |
| `function ({ x, y } = {})` | 0 | The whole pattern has a default |
| `function ([first, second])` | 1 | One array pattern, one parameter |
| `function (a = undefined)` | 0 | Any default stops the count, even `undefined` |
The rule applies to every function form: declarations, expressions, arrow functions, methods, and class constructors. For a class, length reports its constructor's parameters.
const arrow = (x, y = 0) => x + y;
class Point {
constructor(x, y, z = 0) {}
}
const obj = { method(a, b) {} };
console.log(arrow.length); // 1
console.log(Point.length); // 2
console.log(obj.method.length); // 2length Versus arguments.length
The two are easy to confuse. function.length is a fixed property of the function, set when the function is defined. arguments.length (or args.length for a rest array) is the number of arguments passed to one particular call.
function show(a, b = 2) {
console.log(`declared: ${show.length}, passed: ${arguments.length}`);
}
show(); // declared: 1, passed: 0
show(1, 2, 3); // declared: 1, passed: 3The engine never uses length to check calls. You can pass any number of arguments to any function. Only code that reads length cares about it.
Who Actually Reads length
Most application code never touches length. Some libraries depend on it, and that is where the rule causes real problems.
Express error handlers
Express decides whether a middleware function handles errors by checking whether it has exactly four parameters, (err, req, res, next). Express checks this through fn.length.
const errorHandler = (err, req, res, next) => {
res.status(500).send(err.message);
};
const brokenHandler = (err, req, res, next = () => {}) => {
res.status(500).send(err.message);
};
console.log(errorHandler.length); // 4: treated as an error handler
console.log(brokenHandler.length); // 3: treated as normal middlewareAdding a harmless-looking default to next silently changes how Express classifies the function. Express then skips your error handler when an error occurs.
Test frameworks
Mocha decides whether a test is callback-based by checking whether the test function declares a parameter (fn.length > 0). If you write it("works", (done) => ...), Mocha waits for done() to be called. If you change the parameter to (done = noop), the length becomes 0, Mocha treats the test as synchronous, and any asynchronous failures go unreported.
Currying helpers
A curry helper keeps collecting arguments until it has fn.length of them, then calls the function.
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
}
return (...more) => curried(...args, ...more);
};
}
const add3 = (a, b, c) => a + b + c;
const addWithDefault = (a, b, c = 0) => a + b + c;
console.log(curry(add3)(1)(2)(3)); // 6
console.log(curry(addWithDefault)(1)(2)); // 3: length is 2, so it runs earlyWith c = 0, the curried function runs as soon as it has two arguments. Depending on what you wanted, that is either convenient or a bug.
Wrappers Lose length
Generic wrappers usually forward arguments with a rest parameter. The wrapper's length is then 0, whatever the original function's length was.
function logged(fn) {
return (...args) => {
console.log("calling with", args);
return fn(...args);
};
}
const multiply = (a, b) => a * b;
console.log(multiply.length); // 2
console.log(logged(multiply).length); // 0If you pass logged(multiply) to curry, it runs immediately with no arguments. length is configurable, so a wrapper can copy the original value across:
function loggedKeepLength(fn) {
const wrapper = (...args) => fn(...args);
Object.defineProperty(wrapper, "length", { value: fn.length });
return wrapper;
}
console.log(loggedKeepLength((a, b) => a * b).length); // 2Plain assignment does not work. length is non-writable, so wrapper.length = 2 is ignored, or throws a TypeError in strict mode. You have to use Object.defineProperty.
Bound functions handle this for you. fn.bind(thisArg, x) produces a function whose length is the original length minus the number of bound arguments, with a minimum of 0.
const volume = (w, h, d) => w * h * d;
console.log(volume.bind(null, 2).length); // 2
console.log(volume.bind(null, 1, 2, 3, 4).length); // 0Decision Guide
- If nothing reads
length, write the signature that reads best. Defaults and rest have no runtime cost tied tolength. - If a framework classifies callbacks by
length, keep the parameters it counts free of defaults and rest, and handle missing values inside the function body. - If you write a wrapper or decorator, decide whether it should keep the original
length, and useObject.definePropertyif it should. - If you write a library, prefer explicit options, such as
curry(fn, arity), over guessing fromlength. The examples above show how unreliable the guess can be.
Exercise
What do these log? function a(x, y, z = 1, ...rest) {} function b({ p, q } = {}, r) {} const c = a.bind(null, 1, 2, 3); console.log(a.length, b.length, c.length);
Show answer
2 0 0. For a, counting stops at z, the first parameter with a default, giving 2. For b, the destructuring pattern itself has a default, so counting stops at the first parameter, giving 0, and r is ignored. For c, the bound length is max(0, 2 - 3) = 0.
Exercise
An Express error handler is written as function handleError(err, req, res, next = noop) {...} and it never runs when a route throws. Explain why, and give the fix.
Show answer
Express recognizes error handlers by checking fn.length === 4. The default on next stops the count at three, so Express treats the function as ordinary middleware and skips it during error handling. Remove the default (function handleError(err, req, res, next)) and, if you need to, deal with a missing next inside the body.
Exercise
Write a function arity(fn, n) that returns a wrapper which forwards all its arguments to fn and reports length n.
Show answer
function arity(fn, n) { const wrapper = (...args) => fn(...args); Object.defineProperty(wrapper, "length", { value: n }); return wrapper; } For example, arity((...xs) => xs.length, 3).length is 3. Object.defineProperty is required because length is non-writable but configurable.