Object Destructuring
Object Destructuring – how to simplify code
When working with JavaScript, we often need to use several properties of an object. Object destructuring allows you to easily extract values without writing lengthy object property access.
It was introduced in ES6 and has become one of the essential tools in modern JavaScript.
const user = {
name: 'Anna',
age: 28,
country: 'Armenia'
};
const { name, age } = user;
console.log(name); // Anna
console.log(age); // 28
Advantages of this method:
const user = {
name: 'Arman',
age: 32
};
const { name: fullName } = user;
console.log(fullName); // Arman
Advantages of this method:
const user = {
name: 'Sona'
};
const { name, age = 18 } = user;
console.log(age); // 18
Advantages of this method:
const user = {
name: 'Ani',
location: {
city: 'Yerevan',
zip: 0010
}
};
const { location: { city } } = user;
console.log(city); // Yerevan
Advantages of this method:
function greet({ name, age }) {
return `Hi ${name}, you are ${age} years old.`;
}
const user = { name: 'Narek', age: 35 };
console.log(greet(user));
Advantages of this method: