Rest with Function.length
You'll learn how rest parameters affect a function's declared arity and the .length property.
What is Function.length?
Every JavaScript function has a .length property that tells you how many named parameters the function expects—its "arity." This is useful for introspection, determining how many arguments a function requires before calling it.
function add(a, b) {
return a + b;
}
console.log(add.length); // 2
How Rest Parameters Affect Length
Here's the key rule: rest parameters are NOT counted in a function's .length property. The .length only counts parameters before the rest parameter.
function greet(greeting, ...names) {
return `${greeting}, ${names.join(' and ')}!`;
}
console.log(greet.length); // 1 (only 'greeting' is counted)
Even though greet can accept many arguments, its .length is 1 because only the first parameter (greeting) is a required, named parameter.
Why Does This Matter?
Think of .length as measuring the function's minimum required interface—the parameters you must provide before any optional "extras." Rest parameters represent an unlimited collection of extras, so they don't increase the required count.
function log(level, category, ...messages) {
console.log(`[${level}] ${category}:`, ...messages);
}
console.log(log.length); // 2
// The function requires 'level' and 'category'
// Everything else is optional/variable
This distinction helps frameworks and libraries understand a function's signature programmatically—useful for dependency injection, routing, middleware, and other patterns that inspect functions before calling them.
Key Takeaway: A function's .length property counts only the named parameters before the rest parameter; rest parameters themselves are excluded because they represent variable-length, optional arguments.