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 have a own property key named length

// arrow function
console.assert(
 Object.hasOwn((x) => x + 1, "length"),
);

// function defined by keyword function
console.assert(
 Object.hasOwn(function ff(x) {
  return x + 1;
 }, "length"),
);
// value of function length property is number of required arguments

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

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

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