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.log(Object.hasOwn((x) => x + 1, "length"));

// function defined by keyword function
console.log(Object.hasOwn((function ff(x) { return x + 1; }), "length"));

// also
console.log(Object.hasOwn(Function, "length"));
console.log(Object.hasOwn(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);