Topic 17 of 37
Array & Object Destructuring
Overview
Destructuring is an ES6 feature that allows you to extract values from arrays or properties from objects into distinct variables in a clean, readable way. It drastically reduces boilerplate code when working with complex data structures.
Syntax
The variable names must match the object keys (unless renamed). Defaults apply if the property is undefined.
Object Destructuring
javascript
const user = { name: "Alice", age: 25, role: "Admin" };
// Extracting properties
const { name, age } = user;
// Renaming variables during extraction
const { role: userRole } = user;
// Providing default values
const { status = "Active" } = user;Array destructuring relies on the order/index of the elements, not keys.
Array Destructuring
javascript
const colors = ["Red", "Green", "Blue"];
// Extracting by position
const [primary, secondary] = colors;
console.log(primary); // "Red"
// Skipping items
const [, , tertiary] = colors; // "Blue"Common Pitfalls
- Trying to destructure 'null' or 'undefined' will throw a TypeError. Always ensure the object exists or provide a fallback: `const { name } = user || {};`
Interview Tips
- Practice nested destructuring (e.g., extracting a city from an address inside a user object).
Real-World Example
Destructuring is the standard way to extract props in React components.
example
javascript
function UserProfile({ name, age, onLogOut }) {
return (
<div>
<h1>{name} ({age})</h1>
<button onClick={onLogOut}>Logout</button>
</div>
);
}