JavaScript destructuring is a convenient way to extract values from arrays or properties from objects into distinct variables. It is a syntax introduced in ES6 that makes code more readable and concise.
1. Array Destructuring
You can unpack elements from an array and assign them to variables in one step.
const numbers = [1, 2, 3];
// Destructuring assignment
const [a, b, c] = numbers;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
*Skipping Elements
*
You can skip unwanted elements.
const numbers = [1, 2, 3, 4];
const [first, , third] = numbers;
console.log(first); // 1
console.log(third); // 3
Using Default Values
Default values can be assigned if the element is undefined.
const numbers = [1];
const [a, b = 2] = numbers;
console.log(a); // 1
console.log(b); // 2
2. Object Destructuring
You can extract properties from an object into variables.
const person = { name: 'John', age: 25 };
// Destructuring assignment
const { name, age } = person;
console.log(name); // 'John'
console.log(age); // 25
Renaming Variables
You can rename the variables during destructuring.
const person = { name: 'John', age: 25 };
const { name: fullName, age: years } = person;
console.log(fullName); // 'John'
console.log(years); // 25
Default Values
Default values can be assigned for missing properties.
const person = { name: 'John' };
const { name, age = 30 } = person;
console.log(name); // 'John'
console.log(age); // 30
3. Nested Destructuring
You can destructure nested objects or arrays.
const person = {
name: 'John',
address: {
city: 'New York',
zip: 10001
}
};
const {
name,
address: { city, zip }
} = person;
console.log(name); // 'John'
console.log(city); // 'New York'
console.log(zip); // 10001
4. Function Parameters Destructuring
Destructuring can also be used in function parameters.
function displayUser({ name, age }) {
Name: ${name}, Age: ${age}
console.log();
}
const user = { name: 'Alice', age: 28 };
displayUser(user); // Name: Alice, Age: 28
Benefits of Destructuring
**
**Readability: Makes the code more concise and readable.
Efficiency: Simplifies the extraction of values from arrays or objects.
Flexibility: Supports default values, renaming, and nested structures.
Top comments (0)