Object destructuring is a powerful feature that allows developers to extract values from objects and bind them to variables using a concise and readable syntax.
Basic Syntax:
Object destructuring is accomplished using curly braces {}
and the colon :
operator. Here's the basic syntax:
const { property1, property2 } = object;
In this syntax, property1
and property2
are the names of the properties you want to extract from the object
.
Example:
Let’s consider a simple example:
const person = {
name: 'John',
age: 30,
city: 'New York'
};
const { name, age, city } = person;
console.log(name); // Output: 'John'
console.log(age); // Output: 30
console.log(city); // Output: 'New York'
In this example, properties name
, age
, and city
are extracted from the person
object and assigned to variables of the same names.
Nested Destructuring:
Object destructuring can also be applied to nested objects. For instance:
const person = {
name: 'Alice',
age: 25,
address: {
city: 'San Francisco',
state: 'California'
}
};
const { name, age, address: { city, state } } = person;
console.log(name); // Output: 'Alice'
console.log(age); // Output: 25
console.log(city); // Output: 'San Francisco'
console.log(state); // Output: 'California'
In this example, both top-level properties (name
and age
) and nested properties (city
and state
within address
) are extracted using destructuring.
Default Values:
You can provide default values for properties that might not exist in the source object:
const person = {
name: 'Bob',
age: 30
};
const { name, age, city = 'Seattle' } = person;
console.log(name); // Output: 'Bob'
console.log(age); // Output: 30
console.log(city); // Output: 'Seattle'
Rest Pattern:
The rest pattern (...rest
) gathers the remaining properties into a new object:
const person = {
name: 'Emma',
age: 28,
city: 'Chicago',
country: 'USA'
};
const { name, age, ...rest } = person;
console.log(name); // Output: 'Emma'
console.log(age); // Output: 28
console.log(rest); // Output: { city: 'Chicago', country: 'USA' }