Function Length Counts Params Before Defaults
Read Function.prototype.length to get how many parameters are declared before the first default, so frameworks can read handler arity.
Code
// Function.prototype.length counts declared parameters up to the first
// one that has a default value; rest parameters add zero. Frameworks
// read it to decide how many arguments a handler expects.
function connect(url, timeoutMs = 5000) {}
function broadcast(...channels) {}
function register(label, { retries = 0 } = {}) {}
function ping(host, port, timeoutMs) {}
console.log('connect :', connect.length); // 1
console.log('broadcast :', broadcast.length); // 0
console.log('register :', register.length); // 1
console.log('ping :', ping.length); // 3
// Making a previously required parameter optional shifts the boundary
function strict(url, options) {}
function lenient(url, options = {}) {}
console.log('required options:', strict.length, '| defaulted:', lenient.length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
connect : 1
broadcast : 0
register : 1
ping : 3
required options: 2 | defaulted: 1How it works
The code’s whole job belongs to the functions connect, broadcast, register and ping.
What to watch for
- The environment needs no preparation beyond having the interpreter or compiler.
Where you would put it to use
Entry signature: function connect(url, timeoutMs = 5000)
Look for the connect :, broadcast :, register : prefixes during the file’s run; they match each line of output to the step that emitted it.
Interactive Tools for This Topic
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `connect`, `broadcast`, `register` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.