DEV Community

Barrios Freddy
Barrios Freddy

Posted on • Updated on

Object destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects. In this case, we are going to see how destructuring works for objects.

const user = {
  userName: 'fbarrios',
  firstName: 'Freddy',
  lastName: 'Barrios',
  address: {
    street: '52',
    zipcode: '110007',
}

const { firstName } = user
console.log(firstName); // Freddy

Enter fullscreen mode Exit fullscreen mode

This is the same as…

const firstName = user.firstName
Enter fullscreen mode Exit fullscreen mode

It is possible to set default values, in case the property doesn’t exist or is undefined.

const { phone = '0000000' } = user
console.log(phone) // 0000000
Enter fullscreen mode Exit fullscreen mode

A property can be renamed when it’s destructured.

const { username: displayName } = user
console.log(displayName); // Freddy
Enter fullscreen mode Exit fullscreen mode

You can rename and set a default value for a property

const { phone: phoneNumber = '0000000' } = user
console.log(phoneNumber) // 0000000
Enter fullscreen mode Exit fullscreen mode

When the object has another one nested it’s destructured in the following way

let { address: { street } } = user
console.log(street) // 52
Enter fullscreen mode Exit fullscreen mode

Destructuring can be used with the arguments of a function

function fullname({firstName, lastName}) {
  return `${firstName} ${lastName}`;
}

console.log(fullName(user)); // Freddy Barrios
Enter fullscreen mode Exit fullscreen mode

Computed property names can be used with the destructuring assignment.

const key = 'username'
const { [key] } = user
Enter fullscreen mode Exit fullscreen mode

Rest operator in object destructuring

This operator (...) collects all properties that weren’t picked off during object destructuring

const { address, …restProperties } = user
console.log(address);
/*
{
  street: '52',
  zipcode: '110007',
}
*/ 
console.log(restProperties); /
{
  userName: 'fbarrios',
  firstName: 'Freddy',
  lastName: 'Barrios',
}
*/
Enter fullscreen mode Exit fullscreen mode

As you can see, object destructuring is very useful and gives us another way to write better code.

Top comments (0)