Array destructuring allows you to extract elements from an array and assign them to variables based on their position in the array. The order of the variables on the left side of the assignment corresponds to the order of the elements in the array.
Object destructuring allows you to extract properties from an object and assign them to variables. The variable names on the left side of the assignment must match the property names in the object.
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
const numbers = [1, 2, 3];
const [, b, ] = numbers;
console.log(b); // Output: 2
const numbers = [1, 2, 3, 4, 5];
const [a, b, ...rest] = numbers;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(rest); // Output: [3, 4, 5]
const person = {
name: 'John',
age: 30
};
const { name, age } = person;
console.log(name); // Output: John
console.log(age); // Output: 30
const person = {
name: 'John',
age: 30
};
const { name: fullName, age: yearsOld } = person;
console.log(fullName); // Output: John
console.log(yearsOld); // Output: 30
const person = {
name: 'John'
};
const { name, age = 25 } = person;
console.log(name); // Output: John
console.log(age); // Output: 25
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // Output: 2
console.log(b); // Output: 1
const person = {
name: 'John',
age: 30
};
function printPersonInfo({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}
printPersonInfo(person); // Output: Name: John, Age: 30
Avoid over - complicating destructuring expressions. If a destructuring statement becomes too long or hard to read, it might be better to break it down into smaller steps.
When using destructuring, use variable names that clearly describe the data they represent. This makes the code more understandable and maintainable.
JavaScript ES6 destructuring for objects and arrays is a powerful feature that can significantly improve the readability and maintainability of your code. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can make your JavaScript code more concise and efficient. Whether you’re swapping variables, extracting values from complex data structures, or passing parameters to functions, destructuring can be a valuable tool in your JavaScript toolkit.