Rest parameters for variable arguments
Quick answer
A rest parameter collects remaining arguments into a real Array. It is useful when a function accepts a variable number of values.
How it works
Use function f(first, ...remaining). Rest must be the final parameter and cannot have a default initializer or trailing comma. An array stores indexed values; here we need only its length, with array operations taught next.
function count(...items) { return items.length; }console.log(count(), count(2, 4, 6));Expected output in Node.js:
0 3The rest array is empty with no arguments.
function extra(first, ...others) { return others.length; }console.log(extra("a"), extra("a", "b", "c"));Expected output in Node.js:
0 2The first argument has its own parameter; rest collects only the remainder.
Common mistakes
Rest collects; spread expands. They share punctuation but occur in different syntactic positions.
Practice
Predict the count when five arguments are sent to extra.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Rest parameters for variable arguments — Knowledge Check
Apply the taught concept and reason about the result.
What type of value is the rest parameter ...items inside a function?
What does function count(...items){return items.length;} called with no arguments return?
What does function restCount(first,...rest){return rest.length;} called with (2,4,8) return?
Where must a rest parameter appear?
How does rest differ from spread syntax?