How to destructure arrays and objects in JavaScript
· Category: JavaScript
Short answer
Destructuring lets you unpack values from arrays and properties from objects into distinct variables using a syntax that mirrors array and object literals.
Steps
- Object destructuring:
javascript const user = { name: "Mia", age: 30, city: "Berlin" }; const { name, age } = user; - Rename variables:
javascript const { name: fullName } = user; - Set defaults:
javascript const { role = "guest" } = user; - Array destructuring:
javascript const [first, second] = [10, 20, 30]; - Nested destructuring:
javascript const { coords: { x, y } } = { coords: { x: 1, y: 2 } };
Tips
- Use destructuring in function parameters for cleaner signatures:
javascript function greet({ name, greeting = "Hi" }) { /* ... */ } - Combine with rest to collect remaining properties:
javascript const { id, ...rest } = obj;
Common issues
- Destructuring
nullorundefinedthrows a TypeError; default the source if necessary. - Forgetting parentheses when destructuring in an assignment expression.