Callback introspection
A higher-order utility can inspect a callback's declared arity before choosing an invocation strategy.
JS Puzzles · Const
Function.length is a numeric property that indicates how many formal parameters a function expects. Defaults stop the count, destructuring counts once, and rest parameters are excluded.
Read a function's length property to inspect how many formal parameters it declares. Counting stops when the first parameter with a default value appears, each destructuring pattern counts once, and a rest parameter does not contribute.
function.lengthA number.
...items adds nothing to Function.length.function greet(name, message = "Hi", ...tags) {}
console.log(greet.length); // 1
console.log(((a, b) => {}).length); // 2
console.log((...args => {}).length); // 0The property counts formal parameters before the first default-valued parameter; destructuring counts as one parameter and rest parameters are excluded.
A higher-order utility can inspect a callback's declared arity before choosing an invocation strategy.
A wrapper can preserve or compare declared parameter counts when adapting functions.
Learning and debugging code can reveal how JavaScript parses different parameter forms.
It is a numeric property describing the number of formal parameters expected by a function. It is not a call-time argument counter.
Follow-up: How does a default parameter affect it? Counting stops at the first default-valued parameter, so later parameters do not increase the value.
A rest parameter is excluded, while a destructuring pattern counts as one parameter. Thus (a, {b}, ...rest) => {} has length 2.
Follow-up: What is the value of ((a = 1, b) => {}).length? It is 0 because the first parameter has a default value.
Function.length describes declared formal parameters, whereas arguments.length reports arguments actually passed to a call. The two values can differ in either direction.
Follow-up: What does Function.length report for the built-in Function constructor? Its value is 1.
arguments.lengthFunctionFunction.prototype