Destructuring takes values out of arrays or objects into variables. Rest collects the leftover items into one array or object. Spread does the opposite: it expands an array or object into separate items.
Destructuring:
- Arrays go by position:
const [first, , third] = arr. - Objects go by property name:
const { id, name: label = 'none' } = user. Herenameis renamed tolabel, with a default of'none'. - Defaults apply only when the value is
undefined. - It also works in function parameters:
function f({ id, ...rest }) {}.
Rest syntax (...):
- It collects the remaining items into a new array or object.
- Examples:
function sum(...nums)andconst { password, ...safe } = user. - It must come last.
Spread syntax (...):
- It expands an iterable (like an array) or an object in place.
- Examples:
Math.max(...nums),[...a, ...b]and{ ...defaults, ...options }. - Object spread copies own enumerable properties. If two objects have the same key, the later one wins.
- The copy is shallow, so nested objects are still shared.
- Destructuring works by position for arrays and by name for objects, with defaults and renaming.
- Defaults are used only when the value is
undefined. - Rest collects the remaining items and must come last.
- Spread expands arrays or objects, and later properties override earlier ones.
- Spread makes shallow copies.