Problem Statement
What does const {name, age} = person do?
Explanation
Object destructuring extracts properties from objects into distinct variables.
It matches variable names to property names. If a property does not exist, the variable is undefined.
You can rename variables, set default values, or destructure nested objects.
Destructuring makes code cleaner when working with objects.
It was introduced in ES6 and is widely used in modern JavaScript, especially in React.
Code Solution
SolutionRead Only
const person = {
name: 'John',
age: 30,
city: 'New York'
};
// Basic destructuring
const {name, age} = person;
console.log(name); // 'John'
console.log(age); // 30
// Rename variables
const {name: userName, age: userAge} = person;
console.log(userName); // 'John'
console.log(userAge); // 30
// Default values
const {name, country = 'USA'} = person;
console.log(country); // 'USA' (default)
// Missing property
const {job} = person;
console.log(job); // undefined
// Rest operator
const {name: n, ...rest} = person;
console.log(n); // 'John'
console.log(rest); // {age: 30, city: 'New York'}
// Nested destructuring
const user = {
name: 'Jane',
address: {
city: 'Boston',
zip: '02101'
}
};
const {address: {city, zip}} = user;
console.log(city); // 'Boston'
console.log(zip); // '02101'
// Function parameters
function greet({name, age}) {
console.log(`${name} is ${age}`);
}
greet(person); // 'John is 30'Practice Sets
This question appears in the following practice sets:
