**Destructuring** is one of ES6's most useful features. It works for objects and arrays in variable declarations, function parameters, and `for...of` loops. Features include **defaults**, **renaming**, **nested** patterns, and **rest**. It's particularly powerful for working with API responses and function options.
1Understanding Destructuring
Destructuring is one of ES6's most useful features. It works for objects and arrays in variable declarations, function parameters, and for...of loops. Features include defaults, renaming, nested patterns, and rest. It's particularly powerful for working with API responses and function options.
Destructure function parameters for named arguments: 'function create({ name, age = 18, role = "user" })' is much cleaner than positional arguments.
// Object destructuring with defaults & renaming
const user = { name: 'Alice', role: 'admin' };
const { name: userName, role, age = 30 } = user;
console.log(userName); // 'Alice' (renamed)
console.log(role); // 'admin'
console.log(age); // 30 (default!)2Practical Example
Here is a real-world application of Destructuring showing how it is used in production JavaScript code.
// Nested + function parameter destructuring
function renderProfile({ name, address: { city, country = 'Unknown' } }) {
console.log(`${name} from ${city}, ${country}`);
}
renderProfile({
name: 'Bob',
address: { city: 'Paris', country: 'France' }
}); // Bob from Paris, France3Best Practices
Follow these guidelines when working with Destructuring:
1. Use defaults in destructuring to handle missing values
2. Destructure in function params for named arguments pattern
3. Use renaming syntax to avoid conflicts: { name: userName }
Tip: Destructure function parameters for named arguments: 'function create({ name, age = 18, role = "user" })' is much cleaner than positional arguments.
// Object destructuring with defaults & renaming
const user = { name: 'Alice', role: 'admin' };
const { name: userName, role, age = 30 } = user;
console.log(userName); // 'Alice' (renamed)
console.log(role); // 'admin'
console.log(age); // 30 (default!)