Destructuring — Arrays & Objects
Destructuring pulls values out of arrays or objects into variables in one line. React props, API responses, and function parameters all use this pattern: const { name, email } = user.
Array destructuring
const colors = ['red', 'green', 'blue'];
const [first, second] = colors;
// first = 'red', second = 'green'
const [, , third] = colors; // skip first two
// third = 'blue'
const [head, ...rest] = colors;
// head = 'red', rest = ['green', 'blue']
Object destructuring
const user = { id: 42, name: 'Alex', email: 'alex@toolliyo.com', role: 'student' };
const { name, email } = user;
const { role: userRole } = user; // rename to userRole
// Default if missing
const { phone = 'N/A' } = user;
🌍 Real-world example — API user profile (React / Node)
async function showProfile(response) {
const data = await response.json();
const { name, email, plan = 'free' } = data.user;
return `${name} (${email}) — ${plan} plan`;
}
// Simulated API object:
showProfile({
json: async () => ({ user: { name: 'Ravi', email: 'ravi@example.com' } })
});Destructuring in function parameters
function printOrder({ orderId, items, total }) {
console.log(`Order #${orderId}: ${items.length} items, ₹${total}`);
}
printOrder({ orderId: 'A100', items: [1, 2], total: 1498 });
⚠️ Common Mistake: Destructuring undefined:
const { x } = null throws. Use defaults: const { x } = obj || {} or optional chaining (Lesson 12 preview).💡 Tip: In React:
function Card({ title, children }) { } — that is object destructuring of props.👨🏫 Teaching note: Pass a nested API JSON on screen; students write destructuring for user.name and address.city.