Object Destructuring
Object Destructuring
Section titled “Object Destructuring”Introduction
Section titled “Introduction”Destructuring is a concise syntax for extracting properties from objects into variables. It’s a powerful ES6 feature.
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 Variables
Section titled “Renaming Variables”const user = { name: 'Alice', age: 25 };
const { name: userName, age: userAge } = user;console.log(userName); // 'Alice'Default Values
Section titled “Default Values”const user = { name: 'Alice' };const { name, age = 18 } = user;console.log(age); // 18 — default usedNested Destructuring
Section titled “Nested Destructuring”const user = { name: 'Alice', address: { city: 'NYC', zip: '10001' }};
const { address: { city, zip } } = user;console.log(city); // 'NYC'Function Parameters
Section titled “Function Parameters”function greet({ name, age }) { return `${name} is ${age} years old`;}
greet({ name: 'Alice', age: 25 });Summary
Section titled “Summary”- Destructuring extracts properties into variables
- Rename with
{ oldName: newName } - Default values with
= - Works great with function parameters