How does destructuring work for objects and arrays?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Destructuring unpacks values from objects or arrays into variables using a pattern that mirrors the structure: { a, b } = obj picks properties by name, [x, y] = arr picks items by position.
Detailed explanation
Object destructuring matches property names, so order doesn't matter, and you can rename ({ name: userName }) or provide defaults ({ age = 18 }). Nested patterns reach into inner structures in one line. Array destructuring works positionally, supports skipping holes ([a, , c]) and defaults, and its rest element collects the tail. The swap idiom [a, b] = [b, a] falls out naturally. In function signatures, destructured parameters give named options with defaults — the pattern behind most modern APIs (e.g., fetch options). Combined with spread it handles immutable updates: ({ ...user, name: 'New' }) clones while overriding. Common uses: pulling data out of API responses, iterating Object.entries, and cleaning up props in React components.
Example
const user = { name: 'Ada', address: { city: 'London' }, roles: ['admin', 'dev'] };
const { name, address: { city }, country = 'UK' } = user;
// name='Ada', city='London', country='UK'
const [primary, ...rest] = user.roles;
// primary='admin', rest=['dev']
function render({ title, size = 'md' }) {
return `${title} (${size})`;
}
render({ title: 'Card' }); // 'Card (md)'Interview tip
Show renaming, defaults and nesting in one compact example — three features in five lines reads as fluency rather than memorization.
Common mistakes
- Misremembering that arrays destructure by key — they use position.
- Forgetting parentheses when destructuring to existing variables: ({a} = obj);