DEV Community

Cover image for Understanding Destructuring in Javascript
Manuel Pascual
Manuel Pascual

Posted on

Understanding Destructuring in Javascript

Object destructuring in Javascript is a must-have for your toolbelt if you want to write clean and concise code.

Basically, it allows you to extract properties from objects and bind them to variables in a single statement.

Also, it can access properties from nested objects and set a default value in case the property doesn't exist.

Here I'll explain to you how to use this powerful Javascript feature.

01. The benefits of destructuring.

First of all, we have to talk about why we need this feature to write cleaner code. Well, suppose you have to extract some properties from an object but doing it in the old fashioned pre-ES2015 way:

var user = {
  name: "John",
  email: "sayhi@johndoe.com",
};

var name = user.name;
var email = user.email;

console.log(name); // > "John"
console.log(email); // > "sayhi@johndoe.com"
Enter fullscreen mode Exit fullscreen mode

In this chunk of code, the property user.name is bound to the variable name and the same thing for the user.email property. This code works well, but imagine if you have to extract more than 2 property values like this example. Easily becomes a little messy requiring a lot of boilerplate.

What if I tell you that this way of extracting properties could be done in just one statement. That's where object destructuring come into play, so let's refactor the above example applying this cool feature:

const user = {
  name: "John",
  email: "sayhi@johndoe.com",
};

const { name, email } = user;

console.log(name); // > "John"
console.log(email); // > "sayhi@johndoe.com"
Enter fullscreen mode Exit fullscreen mode

const { name, email } = user is an object destructuring assignment. This statement defines two variables, name and email, and assigns to them the values of the properties user.name and user.email from the user object correspondingly.

That being so, object destructuring can help us to write less code in a cleaner way. But that's not all, so let's continue reviewing the different options of this awesome feature.

02. Setting default values.

There are cases where you can't be sure if a property exists inside the object that is being destructured, so setting default values becomes quite handy:

const dinosaur = {
  name: "Tracy",
  phone: "54080071882",
};

const { name, email } = dinosaur;

console.log(name); // > "Tracy"
console.log(email); // > undefined
Enter fullscreen mode Exit fullscreen mode

After destructuring, the new variable email is undefined because the property email doesn't exist in the object dinosaur. But don't panic! We can set a default value if we wish to. Here's the basic syntax:

const { identifier = defaultValue } = expression;
Enter fullscreen mode Exit fullscreen mode

Where expression should evaluate to an object and identifier corresponds to a property of that object. In case it doesn't exist, identifier is assigned with defaultValue.

03. Aliasing feature.

Sometimes is useful to create variables of different names than the properties. In those cases, you can set an alias for the extracted property. Let's see an example:

const car = {
  brand: "Toyota",
  owners: ["John", "George", "Sabrina"],
};

const { brand: carBrand, owners: carOwners } = car;

console.log(carBrand); // > "Toyota"
console.log(carOwners); // > ["John", "George", "Sabrina"]
Enter fullscreen mode Exit fullscreen mode

Pay attention to the : inside the destructuring syntax. This colon allows you to set a different variable name after it. Keep in mind that both brand and owners are not variables cause we replace their names with carBrand and carOwners aliases correspondingly.

04. Extracting properties from nested objects.

One of my favorite features of object destructuring is the possibility to extract properties that are inside nested objects.

Previously, the properties that we extracted had primitive data types (e.g. strings) but it is common to see objects inside other objects. In such cases, we still can destructure and access deeper properties. Here's an example of this:

const blogPost = {
  title: "Javascript is awesome!",
  author: {
    firstName: "John",
  },
};

const { title, author: { firstName } } = blogPost;

console.log(title); // > "Javascript is awesome!"
console.log(firstName); // > "John"
Enter fullscreen mode Exit fullscreen mode

Here, we also destructured the object that is inside the author property of blogPost. We took the firstName property and at the same time, we declared a variable with that name and assigned its value ("John"). Remember that we only use author to be able to extract its properties, so if you log author into the console, you'll get undefined.

05. Power up with the rest operator.

The rest operator is useful to grab the remaining properties after destructuring. Let's see it in a basic example:

const image = {
  title: "Amazing image.",
  url: "https://imageurl.com/",
};

const { title, ...otherProps } = image;

console.log(title); // > "Amazing image."
console.log(otherProps); // > { url: "https://imageurl.com/"}
Enter fullscreen mode Exit fullscreen mode

In the above example, we extract the title and with the rest operator we collect the remaining url property into the variable otherProps.

One thing to notice is that otherProps is a plain object. With that said, by using the rest operator like this we get an object with all the remaining properties. So, following this example, if you want to get the url you have to use dot notation:

console.log(otherProps.url); // > "https://imageurl.com/"
Enter fullscreen mode Exit fullscreen mode

06. Array destructuring.

Last but not least, you can also use destructuring with Arrays but with a little difference. Instead of using curly braces, we have to surround the identifiers within square brackets:

const [firstName, age] = ["Sabrina", 25];

console.log(firstName); // > "Sabrina"
console.log(age); // > 25
Enter fullscreen mode Exit fullscreen mode

In this example, we collect the array items following the order in which they appear. This means that if we want to extract an additional value with no index inside the Array, the identifier will be assigned with undefined. Here's an example:

const [carBrand, carModel] = ["BMW"];

console.log(carBrand); // > "BMW"
console.log(carModel); // > undefined
Enter fullscreen mode Exit fullscreen mode

As we can see, there isn't an element in the index position 1, so instead of throwing an error, Javascript is smart enough to bind the value undefined to carModel.

07. Summing up.

In this article, we talked about some of the important concepts of destructuring in Javascript. We saw that it is a powerful feature that allows us to write cleaner, concise, and more understandable code.

If you want to know more about this feature, I invite you to take a look at the MDN Documentation.

Got any questions? Leave a comment below.

Thank you for reading :)

Top comments (1)

Collapse
 
anshul_gupta profile image
Anshul Gupta

Thank you @pascualmj ,
I was using destructing for a long time but I didn't know its that strong.