Destructuring in JavaScript - Part I

Destructuring in JavaScript - Part I

Ā·

5 min read

You might have come across a concept called Destructuring in JavaScript. For those out there who are not familiar with this concept, this article series is for you. šŸ˜„

Iā€™ll be covering everything about destructuring in 3 parts. In this part, you will learn all about Object Destructuring.

So, let's begin, shall we?

What is Destructuring and Why should we use it?

Destructuring allows us to extract values from arrays, or properties from objects, and elegantly tie them to variables.

To understand the ā€œwhyā€ part, let us take an example.

let userInfo = {
      userID: 101,
      name: "Lily",
      email: ā€œlily23@dev.com ā€,
      address: {
         city: ā€œSpringpine",
         state: ā€œMerriton",
         country: ā€œGliabiaā€,
      }
};

If you want to obtain values of the object above, you would do something like this:

let userID = userInfo.userID;
let name = userInfo.name;
let city = userInfo.address.city;
let state = userInfo.address.state;
let country = userInfo.address.country;

While this probably won't seem to be a very remarkable problem, there are few things you should consider:

  • In real life, projects have a huge codebase. You'll have to manage a lot of nested objects. With destructuring, the same can be accomplished with a lot simpler syntax.

  • Secondly, why should you use longer syntax when you can take advantage of javascript destructuring?

So, now you know "why" you should think about destructuring.

Let's see how destructuring helps in accomplishing the same with less code.

const { userID, name } = userInfo;

console.log(userID);   //101
console.log(name);  //Lily

As you can see, we only had to write one line of code and also reduced the repetitive process of calling object names and keys. šŸ˜²

Notice that we used curly braces on the left side as we are destructuring an object. It means that the JavaScript engine will look in the userInfo object for the exact name as the constant we declared. So, the names on the left should match the names in the object.

Renaming the variable

What if I want to use a different variable name?

In that case, you can set an alias for that specific property.

Letā€™s see the code:

const { userID, name: userName, email: userEmail   } = userInfo;

console.log(userID);   //101
console.log(userName);  //Lily
console.log(userEmail);   //lily23@dev.com

The colon : allows you to set a different name for your variable. Here, we have given a different variable name for the name and email property.

Note: Make sure you are using the new variable name to access the value else you will get an error.

Can I change the order?

Absolutely.

Example: Letā€™s declare variables in a different order than in the object

const { email, name, userID } = userInfo;

console.log(email); // lily23@dev.com
console.log(name); //lily

Changing the order does not affect destructuring as objects store data in key: value pairs and not by index where order matters.

Missing Element

What happens if I destructure a missing element? šŸ¤”

When you try to access a variable that is not defined in the object, the variable gets assigned the value of undefined.

Example:

let userInfo = {
      userID: 101,
      name: "Lily",
      email: "lily23@dev.com",
      address: {
         city: "Springpine",
         state: "Merriton",
         country: "Gliabia",
      }
   }; 

const { name, jobTitle } =  userInfo;

console.log(name); // Lily
console.log(jobTitle); // undefined

As you can see, jobTitle is not declared in the userInfo object. Hence it gets assigned the value of undefined.

Now, there is an option to assign a default value to the missing element instead of undefined.

Default Values

Default values are helpful when you have optional parameters in your code.

Letā€™s see how to assign a default value to a variable,

const { name, jobTitle = 'Security Princess' } =  userInfo;

console.log(jobTitle); // Security Princess

Itā€™s that easy.

You can set both an alias as well as a default value for a variable.

const { name, jobTitle : jobRole = 'Security Princess' } =  userInfo;

console.log(jobRole); // Security Princess

Cool right? šŸ˜®ā€šŸ’Ø

Accessing Nested Objects

JavaScript objects tend to be complex. To access those complex nested objects, you can use object destructuring.

Letā€™s take the same userInfo object,

let userInfo = {
      userID: 101,
      name: "Lily",
      email: ā€œlily23@dev.com ā€,
      address: {
         city: ā€œSpringpine",
         state: ā€œMerriton",
         country: ā€œGliabiaā€,
      }
   };

To access the value of country from the userInfo object, the code will be:

const { address : { country } } = userInfo;

You can go as deep as you want in nesting by just adding more curly braces.

The syntax to access object inside another object:

const { prop1 : { prop2 : { ā€¦ } } } = object;

Rest Operator

Rest operator can be used when you want to pack the rest of the properties into another object.

Letā€™s say you only want the email of the user and want the rest to be stored in a different object called userDetails.

We can do it like this,

const { email, ā€¦userDetails } = userInfo;

console.log(email, userDetails );
//{ userID: 101, name: "Lily",  address: { city: ā€œSpringpine", state: ā€œMerriton", country: ā€œGliabiaā€ } }

Note: The rest operator ā€¦ should be used in the end i.e., just before closing the curly brace. Using it in the middle or at the start will throw an error.

Passing object to a Function

Traditionally, we used to directly send the object to the function and then access its properties using a dot . operator like below.

function getInfo( user ){
console.log('Name: ${user.name}, Email: ${user.email}');
};

getInfo( userInfo );

Using object destructuring, we can rewrite it as follows:

function getInfo( { name, email } ){
console.log('Name: ${name}, Email: ${email}');
};

getInfo( userInfo );

Notice the curly braces { } in the function arguments.

Destructuring is especially useful inside a function definition. I'll be explaining it in detail in the coming articles.

Parting Thoughts

Object destructuring is a must-have if you want to write clean and concise code.

It takes a bit of getting used to, but quickly youā€™ll be pretty comfortable making use of it in your own code.

I hope you enjoyed this article or thought that it is useful. Please share, comment, and give a few šŸ‘ if you liked it.

Ā