JavaScript Course
JavaScript
/
Beginner

Rest Parameters

Definition

The rest parameter syntax `...` allows a function to accept an indefinite number of arguments as an array.

Explain Like I'm New

Imagine a garbage bag at the end of a function signature. It sweeps up any 'extra' arguments passed to the function that didn't get their own specific variable name, and dumps them all into an array.

Real World Example

A `sum(...numbers)` function that can accept `sum(1, 2)` or `sum(1, 2, 3, 4, 5)` and handles them elegantly by reducing the array.

Common Use Cases

  • •Replacing the old `arguments` object
  • •Functions with variable arity

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What is the difference between Spread and Rest?

intermediate

  • Can the rest parameter be placed at the beginning of the arguments list?

advanced

  • Why is Rest preferred over the `arguments` keyword?

Flash Cards

Question

Spread vs Rest?

Click to reveal answer
Answer

They look exactly the same (`...`). Rest is used to COLLECT multiple elements and condense them into a single array (e.g., in function parameters). Spread is used to UNPACK an array into multiple individual elements (e.g., in array literals or function calls).

Question

Can it be placed at the beginning?

Click to reveal answer
Answer

No. The rest parameter MUST be the very last parameter in the function definition, otherwise a SyntaxError is thrown. It scoops up the 'rest' of the arguments.