Function LengthLoading saved progress…

Function Length

Implement functionLength(fn) that returns the number of declared parameters of fn — its arity. The catch is in what "declared parameters" means: JavaScript counts only the parameters before the first one that has a default value or is a rest parameter. So (a, b) has arity 2, but (a, b = 1) has arity 1, and (...args) has arity 0.

Signature

// fn: a function (arrow or regular function declaration).
// returns: the number of declared parameters counted up to — but not
//          including — the first default-valued or rest parameter.
function functionLength(fn): number;

Examples

functionLength((a, b) => {});          // → 2
functionLength((a, b = 1) => {});      // → 1  (params from the first default on are excluded)
functionLength((...args) => {});       // → 0  (a rest param is excluded)
functionLength((a, b, ...rest) => {}); // → 2  (params before the rest still count)
functionLength(() => {});            // → 0
functionLength(({ x, y }) => {});    // → 1  (a destructured param is still one param)
function add(a, b, c) { return a + b + c; }
functionLength(add);                 // → 3  (works on regular functions too)

Notes

  • Defaults truncate the count. A parameter with a default value, and every parameter after it, is excluded — even if those later params have no default of their own.
  • A rest parameter never counts. ...args always contributes 0.
  • Destructuring is one parameter. ({ x, y }) or [a, b] in the parameter list is a single declared parameter, not two.
  • Both function forms work. Arrow functions and regular function declarations are treated the same.
  • Don't parse the source. You do not need to read the function's text — the engine already exposes this number directly.
Loading editor…