23 Feb 2024
Destructuring in JavaScript is a convenient way to extract values from arrays or objects and assign them to variables. It allows you to unpack values from arrays or properties from objects into distinct variables, which can make your code cleaner and more concise.
Array Destructuring:
Array destructuring allows you to unpack values from arrays into separate variables.
Example:
const numbers = [1, 2, 3, 4, 5];
// Destructuring assignment
const [a, b, c] = numbers;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 4
Object Destructuring:
Object destructuring allows you to extract properties from objects and assign them to variables with the same name as the property.
Example:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
// Destructuring assignment
const { firstName, lastName, age } = person;
console.log(firstName); // Output: John
console.log(lastName); // Output: Doe
console.log(age); // Output: 30
You can also provide default values while destructuring, which will be used if the corresponding property or value is undefined.
Example:
const person = {
firstName: 'John',
lastName: 'Doe'
};
// Destructuring assignment with default values
const { firstName, lastName, age = 25 } = person;
console.log(firstName); // Output: John
console.log(lastName); // Output: Doe
console.log(age); // Output: 25 (default value)
Destructuring can also be used with function parameters, allowing you to directly extract values from objects passed to functions.
Example:
function printPersonInfo({ firstName, lastName, age }) {
console.log(`${firstName} ${lastName} is ${age} years old.`);
}
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
printPersonInfo(person); // Output: John Doe is 30 years old.
Destructuring is a powerful feature in JavaScript that can help you write cleaner and more expressive code by reducing repetition and making your intentions clearer.