Glossary / Destructuring
Destructuring
Destructuring extracts values from arrays or object properties into bindings or assignment targets. It is useful for unpacking function results, configuration, and data records. Destructuring is syntax, not a clone operation: when a property contains an object, the new binding refers to that same nested object.
Object and array patterns
const user = { id: 7, name: "Ada", meta: { active: true } };
const { id, name: displayName = "Anonymous", ...other } = user;
const [first, , third = "fallback", ...rest] = ["a", "b"];
Object patterns match property names; name: displayName renames the local binding. Array patterns consume iterator values by position and can skip values. Defaults apply only when the extracted value is undefined, not null. Object rest collects remaining enumerable own properties; array rest collects remaining iterator values.
Destructuring a null or undefined source throws. Use a fallback source only when absence is expected, and avoid hiding a required-data defect with { } = input || {}. Assignment destructuring can be confused with a block statement at the start of an expression, so parentheses may be required. Nested patterns can become difficult to read and can fail partway through when shape assumptions are wrong.
Function parameters
Destructured parameters can document expected configuration fields, but use a default object only if the parameter itself may be omitted: function render({ theme = "light" } = {}) {}. Validate external input before destructuring when it may have malformed shape.
Interview questions
- Do defaults apply when a value is null? No; only undefined triggers the default.
- How rename a property?
{ sourceName: localName }. - Does destructuring clone a nested object? No; it binds the existing reference.
- Why can destructuring throw? Nullish source or missing required iteration/shape assumptions can fail.