JavaScript arguments Objects and Rest Parameters
Quick answer
Ordinary functions generally have an arguments object representing actual call arguments. Rest parameters gather remaining arguments into a real array.
How it works
arguments.length is the actual count, while fn.length describes declared parameters before the first default or rest parameter. Rest arrays omit earlier named parameters. Arrows have no own arguments binding. Sloppy ordinary functions with simple parameter lists may map arguments indices to parameter bindings; strict functions and non-simple parameter lists do not.
function inspect(first, ...rest) { return [arguments.length, rest.length, Array.isArray(arguments), Array.isArray(rest)]; }console.log(JSON.stringify(inspect(1, 2, 3)));Expected output in Node.js:
[3,2,false,true]The arguments object contains all arguments; rest contains two.
function f(a, b = 0, ...rest) { return arguments.length; }console.log(f.length, f(1, 2, 3, 4));Expected output in Node.js:
1 4Declared length stops before the first default; actual count is four.
Common mistakes
Prefer explicit rest parameters to relying on legacy arguments aliasing.
Practice
Compare a function called with zero arguments and with four arguments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript arguments Objects and Rest Parameters — Knowledge Check
Apply the taught concept and predict the output.
Which value is a real Array?
Does an arrow function introduce its own arguments binding?
What does arguments.length measure?
What is the exact console output in JavaScript arguments Objects and Rest Parameters example 1?
function inspect(first, ...rest) { return [arguments.length, rest.length, Array.isArray(arguments), Array.isArray(rest)]; }console.log(JSON.stringify(inspect(1, 2, 3)));What is the exact console output in JavaScript arguments Objects and Rest Parameters example 2?
function f(a, b = 0, ...rest) { return arguments.length; }console.log(f.length, f(1, 2, 3, 4));