JavaScript Rest Destructuring: Collect Remaining Values
Quick answer
Rest in a destructuring pattern collects values not consumed by earlier bindings. It lets a program separate a head from a tail or selected keys from a record.
How it works
const [head, ...tail] = list builds an array from remaining iterator values. const {id, ...details} = record copies remaining enumerable own properties, including eligible symbols. The rest element or property must be last; a trailing comma after it is invalid. Neither form deep-clones nested values.
const [first, ...tail] = [4, 5, 6];console.log(first, tail.join(","));Expected output in Node.js:
4 5,6The first value is bound separately.
const {id, ...data} = {id: 8, name: "Ada", stock: 2};console.log(Object.keys(data).join(","));Expected output in Node.js:
name,stockThe selected id key is excluded from the rest object.
Common mistakes
Rest collects; spread expands. They share spelling but are different grammar forms.
Practice
Separate an ID from a record and preserve the remaining public fields.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Rest Destructuring: Collect Remaining Values — Knowledge Check
Apply the taught concept and predict the output.
What type is the tail in const [head, ...tail] = list?
Where must a rest property occur in an object binding pattern?
Does object rest copy inherited keys?
What is the exact console output in JavaScript Rest Destructuring: Collect Remaining Values example 1?
const [first, ...tail] = [4, 5, 6];console.log(first, tail.join(","));What is the exact console output in JavaScript Rest Destructuring: Collect Remaining Values example 2?
const {id, ...data} = {id: 8, name: "Ada", stock: 2};console.log(Object.keys(data).join(","));