DEV Community

Cover image for Use Object Destructuring like a PRO 😎
Yuvaraj
Yuvaraj

Posted on • Originally published at yuvaraj.hashnode.dev

Use Object Destructuring like a PRO 😎

Hello everyone 👋,

In this article, I'm going to share how to use the Destructuring assignment effectively with real time example for Objects.

Lets, begin with what is Destructuring Assignment?

From MDN,

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

The definition might be confusing for few, so let's break this definition to understand it better. We can break it into 2 parts.

  1. The destructuring assignment syntax is a JavaScript expression.
  2. Makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

The 1st part tells that it is an JavaScript expression which is self explanatory and 2nd part tells that it used to unpack values.

What does unpack values mean?

First, let's understand with real world example.

Imagine, you have a bag with lot of items in it which is actually packed. When you unpack the bag, you take some items from it.

Similarly, in JavaScript world, Array/Object is a bag and you unpack(take) some items from it.

Object Destructuring

Object destructuring helps to unpack keys from an object, assign default values to unavailable key and set an alias to the key.

Unpack keys from Object

Imagine you have an user object that has user information like first name, last name, phone and address.

const user = {
     firstName: 'John',
     lastName: 'Doe',
     phone: '9999999999',
     address: 'India',
     preferences: {
         mode: 'light', // light (or) dark mode
         autoSave: true   
    }
}
Enter fullscreen mode Exit fullscreen mode

To get the first name and phone from user object, we used to retrieve with .(dot) notation or user[key-name].

// dot notation
const firstName = user.firstName;
const phone = user.phone;
console.log(firstName); // John
console.log(phone); // 9999999999

// key inside object
const firstName = user['firstName'];
const phone = user['phone'];
console.log(firstName); // John
console.log(phone); // 9999999999
Enter fullscreen mode Exit fullscreen mode

But, with Object Destructuring, we can unpack the firstName and phone in a single line.

const { firstName, phone } = user;
console.log(firstName); // John
console.log(phone); // 9999999999
Enter fullscreen mode Exit fullscreen mode

*Note: * The exact key should be put in the {} to access the specific value. In our example, we have one key as phone. We cannot access phone by writing const { phone } = user;

Wait, but, what will happen if we try to unpack currency from user object? 🤔

Assigning Default value to key

const { firstName, phone, currency } = user;
console.log(currency); // undefined
Enter fullscreen mode Exit fullscreen mode

Since currency is not available in the user object, it gives undefined as a response.

But, you need to handle this scenario to set USD as a default currency value when currency is undefined. To handle this, you would simply write it as,

const currency = user.currency;
console.log(currency); // undefined
if (!currency) {
   currency = 'USD';
}
console.log(currency); // USD
Enter fullscreen mode Exit fullscreen mode

But with destructuring, you can assign the default value to currency as,

const { firstName, phone, currency = 'USD' } = user;
console.log(currency); // USD

Enter fullscreen mode Exit fullscreen mode

Wow, isn't it wonderful? 😍

It's readable, clean and simplified with minimal change. Let's go into little deep.

How about you want to have an alias to a property?

Assigning Alias to key

Previously, we used to achieve this with by creating one more new property in the new line.

const { firstName, phone, currency = 'USD' } = user;
const mobileNumber = phone;
console.log(mobileNumber); // 9999999999
Enter fullscreen mode Exit fullscreen mode

But, with Object destructuring, it can be even simplified as,

const { firstName, phone: mobileNumber, currency = 'USD' } = user;
console.log(mobileNumber); // 9999999999
Enter fullscreen mode Exit fullscreen mode

You just need to put an alias key by adding :(colon) and alias key before the original key.

Destructuring with Nested Object.

Let's go deeper with nested object.

How about accessing the autoSave key inside the preferences?

Without object destructuring, the code can be written as,

const autoSave = user.preferences.autoSave;
Enter fullscreen mode Exit fullscreen mode

With Object destructuring, we can access the nested object by adding {} again after the root key (i.e preferences). So, it can be written as below. Additionally, alias and default values can be set to it.

const { preferences: { autoSave } } = user;

// with default value
const { preferences: { autoSave = false } } = user;

// with alias key
const { preferences: { autoSave: saveAutomatically } } = user;

// with default value + alias key
const { preferences: { autoSave: saveAutomatically = false } } = user;
Enter fullscreen mode Exit fullscreen mode

To sum up everything, let's compare the code without object destructuring and with destructuring.

Without Object Destructuring,

const user = {
     firstName: 'John',
     lastName: 'Doe',
     phone: '9999999999',
     address: 'India',
     preferences: {
         mode: 'light', // light (or) dark mode
         autoSave: true   
    }
};

// Unpacking values
const firstName = user.firstName;
const phone = user.phone;
const currency = user.currency;

console.log(firstName); // John
console.log(phone); // 9999999999
console.log(currency); // undefined

// Assigning default values
if (!currency) {
   currency = 'USD';
}
console.log(currency); // USD

// Setting Alias to a key
const mobileNumber = phone;
console.log(mobileNumber); // 9999999999

// accessing key from nested object
const autoSave = user.preferences.autoSave;
console.log(autoSave); // true
Enter fullscreen mode Exit fullscreen mode

With Object Destructuring,

const user = {
     firstName: 'John',
     lastName: 'Doe',
     phone: '9999999999',
     address: 'India',
     preferences: {
         mode: 'light', // light (or) dark mode
         autoSave: true   
    }
};

// Unpacking values + Assigning default values + Accessing key from nested object
const { firstName, phone: mobileNumber, currency = 'USD', preferences: { autoSave }  } = user;
console.log(firstName); // John
console.log(mobileNumber); // 9999999999
console.log(currency); // USD
console.log(autoSave); // true
Enter fullscreen mode Exit fullscreen mode

Yay! It's simplified and much readable. Thanks to Object Destructuring. 😍🎉

In this article, we learned about Object Destructuring. In this next article, we will learn about Array Destructuring.

Meanwhile, you can Checkout the Object Destructuring demo in CodeSandbox.

Top comments (0)