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

  1. Object destructuring: javascript const user = { name: "Mia", age: 30, city: "Berlin" }; const { name, age } = user;
  2. Rename variables: javascript const { name: fullName } = user;
  3. Set defaults: javascript const { role = "guest" } = user;
  4. Array destructuring: javascript const [first, second] = [10, 20, 30];
  5. 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 null or undefined throws a TypeError; default the source if necessary.
  • Forgetting parentheses when destructuring in an assignment expression.