Object Destructuring
Object Destructuring
Section titled “Object Destructuring”Introduction
Section titled “Introduction”Object destructuring extracts properties from objects into variables with matching names.
Basic Destructuring
Section titled “Basic Destructuring”const user = { name: 'Alice', age: 25, email: 'alice@email.com' };
const { name, age } = user;console.log(name); // 'Alice'console.log(age); // 25Renaming
Section titled “Renaming”const { name: userName, age: userAge } = user;console.log(userName); // 'Alice'console.log(userAge); // 25Default Values
Section titled “Default Values”const { name, role = 'user' } = user;console.log(role); // 'user' (default)Nested Destructuring
Section titled “Nested Destructuring”const data = { user: { name: 'Bob', address: { city: 'NYC' } } };const { user: { name, address: { city } } } = data;console.log(name); // 'Bob'console.log(city); // 'NYC'Summary
Section titled “Summary”- Property names must match (or use renaming)
{ prop: newName }renames a property{ prop = default }sets a default value- Works with nested objects