The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
It is a powerful ES6 feature that can make your code more concise and readable.
Array destructuring allows you to unpack values from an array into separate variables in a single expression.
const fruits = ["Apple", "Banana", "Cherry"];// Unpack the array into variables const [a, b, c] = fruits;
console.log(a); // "Apple" console.log(b); // "Banana" console.log(c); // "Cherry"
You can use a comma to skip over elements you don't need.
const numbers = [1, 2, 3, 4, 5];// Skip the second and fourth elements const [first, , third, , fifth] = numbers;
console.log(third); // 3
...)You can use the rest operator (...) to assign the rest of an array to a new array variable.
const numbers = [1, 2, 3, 4, 5];const [first, second, ...rest] = numbers;
console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5]
Object destructuring allows you to unpack properties from an object into variables. The variable names must match the property keys.
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
// Unpack properties into variables
const { firstName, lastName, age } = person;
console.log(firstName); // "John"
console.log(age); // 30
You can assign the property to a new variable name using a colon :.
const person = { firstName: "John", lastName: "Doe" };
// Unpack 'lastName' into a new variable called 'surname'
const { firstName, lastName: surname } = person;
console.log(surname); // "Doe"
You can provide a default value for a property in case it does not exist on the object.
const person = { firstName: "John" };
// 'age' does not exist, so it will use the default value 25
const { firstName, age = 25 } = person;
console.log(age); // 25
Given `const person = { name: 'Alice', age: 30 };`, how do you destructure the `name` property into a variable called `userName`?