Что такое деструктуризация?
Destructuring — это способ присваивания переменных из массива или объекта. Она позволяет легко получить доступ к свойствам объекта или элементам массива и присвоить их значения другим переменным.
Синтаксис деструктуризации:
- Массивы:
const [first, second] = array;. - Объекты:
const { prop1, prop2 } = object;.
Примеры использования деструктуризации
1. Деструктуризация массивов
const fruits = ["Apple", "Banana", "Cherry"];
const [firstFruit, secondFruit] = fruits;
console.log(firstFruit); // "Apple"
console.log(secondFruit); // "Banana"2. Деструктуризация объектов
const person = { name: "John", age: 30 };
const { name, age } = person;
console.log(name); // "John"
console.log(age); // 303. Переименование свойств
const user = { fullName: "Jane Smith", birthYear: 1990 };
const { fullName: name, birthYear: year } = user;
console.log(name); // "Jane Smith"
console.log(year); // 19904. Default values
const config = { theme: "dark" };
const { theme = "light", language = "English" } = config;
console.log(theme); // "dark"
console.log(language); // "English"5. Nested destructuring
const nestedObj = { profile: { name: "Bob", age: 25 } };
const { profile: { name, age } } = nestedObj;
console.log(name); // "Bob"
console.log(age); // 25Destructuring — это мощный инструмент, который помогает быстро и удобно извлекать данные из массивов и объектов. Используйте его, чтобы сделать ваш код более читаемым и коротким. Это сделает разработку более приятной и продуктивной.