CKTIS / JavaScript
`Function.length` and function arity
`fn.length` describes a function's expected arity, while `arguments.length` counts the arguments supplied in a particular call.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
fn.length
Function.length
Function.prototype.length
fn.bind(thisArg, ...presetArgs).length
arguments.lengthFunction.length and arity are related: arity is about how many parameters a function takes, and JavaScript exposes an expected count as the numeric property fn.length. It is not a method or a call requirement. The built-in constructor itself has Function.length equal to 1; the callable Function.prototype has length equal to 0.
For a function defined in source code, count parameters from the left up to, but not including, the first parameter with a default for the whole parameter. That parameter and all later parameters are excluded. A rest parameter such as ...tail never counts. A destructuring pattern counts as one parameter: the inner default in { x = 0 } does not stop the count, but the outer = {} in { x = 0 } = {} does.
Inside an ordinary function, arguments.length counts the arguments actually supplied in that call, including an explicit undefined. Arrow functions have no arguments of their own; with (...args) as the entire parameter list, args.length counts all their arguments. A rest array after named parameters contains only the arguments left over after those parameters.
For a function with an unchanged, finite integer own length, bind subtracts the number of preset arguments and floors the result at zero. thisArg does not count. The initial length property is non-writable and non-enumerable, but configurable. Do not use it to validate calls: JavaScript allows a different argument count, and the outcome depends on the function.
Examples
{
function inspect({ x = 0 }, y = 10, z, ...tail) {
return `${arguments.length}:${tail.length}`;
}
console.log(inspect.length);
console.log(inspect.bind(null, {}).length);
console.log(inspect({}));
console.log(inspect({}, undefined, 3, 4, 5));
console.log(Function.length);
console.log(Function.prototype.length);
}Result
1 0 1:0 5:2 1 0
`inspect.length` is `1` because only `{ x = 0 }` counts. Binding `{}` brings it to `0`. In `1:0` and `5:2`, the first number counts all supplied arguments and the second counts only the items in `tail`. The explicit `undefined` counts as an argument even though it triggers the default for `y`.
Related lessons
- JavaScript · Lesson 21 · Advanced · Version: 4
Sources
- ECMAScript® 2024 Language Specification — Static Semantics: ExpectedArgumentCount
- ECMAScript® 2024 Language Specification — Function Instances: length
- ECMAScript® 2024 Language Specification — Function.prototype.bind
- Function: length - JavaScript | MDN
- The arguments object - JavaScript | MDN
- Rest parameters - JavaScript | MDN