JS: Function Length Property

By Xah Lee. Date: . Last updated: .

Every function has a own string property "length", including:

Its value is total count of required parameters. (exclude parameters that have Argument Default Value, and exclude Rest Parameters)

// every function has a own property length

const f1 = ((x) => x + 1);

function f2(x) {
  return x + 1;
}

console.log(
  Reflect.apply(Object.hasOwnProperty, f1, ["length"]),
  Reflect.apply(Object.hasOwnProperty, f2, ["length"]),
);

console.log(
  Reflect.apply(Object.hasOwnProperty, Function, ["length"]),
  Reflect.apply(Object.hasOwnProperty, Function.prototype, ["length"]),
);
// value of function length property is number of required arguments

console.log((() => []).length === 0);
console.log(((x) => [x]).length === 1);
console.log(((x, y) => [x, y]).length === 2);

// param with default value is excluded
console.log(((x, y = 4) => [x, y]).length === 1);

// rest param is excluded
console.log(((x, ...y) => [x, y]).length === 1);

JavaScript, Function