Advertisement
Advanced JavaScript, Destructuring, Spread & Rest

Why must the rest element be the LAST element in a destructuring pattern?

Short answer

Rest collects 'everything remaining' after the named elements are extracted, so its position only makes sense as the final element — putting it earlier would make the remaining count ambiguous, and JavaScript throws a SyntaxError.

Save JavaScript mock interview
Advertisement
AModel answer
Rest collects 'everything remaining' after the named elements are extracted, so its position only makes sense as the final element — putting it earlier would make the remaining count ambiguous, and JavaScript throws a SyntaxError.
const [first, ...rest] = [1, 2, 3, 4]; // valid: rest = [2,3,4]
// const [...rest, last] = [1,2,3]; // SyntaxError
Real-world example
Splitting an array into its head and tail for recursive-style processing.
Likely follow-ups
  • Does the same last-position rule apply to object rest destructuring?
Related topics