A practical guide to object destructuring in JavaScript
Tags: javascript, codenewbie, beginners, es6
Published: 2021-04-27 05:54:00

`Object` in JavaScript is used to store multiple values as a complex data structure. We create objects with curly braces(`{...}`) and one or more properties separated by comma(`,`) symbols. Each of the properties is a key-value pair separated by the colon(`:`) symbol. The key must be a string or JavaScript Symbol type. The value can be of any type, including another object.

Here is an example of an object with six properties. The value of the `name` key is of type string whereas, and it is a number for the `age` and `std` keys. The `subjects` key value is an array. The value of `parents` and `address` are objects.

```js
const student = {
 'name': 'John Williamson',
 'age': 9,
 'std': 3,
 'subjects': ['Maths', 'English', 'EVS'],
 'parents': {
   'father': 'Brown Williamson',
   'mother': 'Sophia',
   'email': 'john-parents@abcde.com'
 },
 'address': {
   'street': '65/2, brooklyn road',
   'city': 'Carterton',
   'country': 'New Zealand',
   'zip': 5791
 }
}
```
Please note: We will use this `student` object in the various examples below.

# Object Destructuring
We store data in objects to retrieve it based on needs at a later point in time. For example, if we want to retrieve the value of the `name` and `city` information from the `student` object, we can do,

```js
const name = student.name;
const city = student.address.city;
console.log(name, city); // John Williamson Carterton
``` 
It works but with a bit more work. First, we use the dot(`.`) notation to access the values. We also need to declare a couple of variables to assign the values accordingly.

We can simplify the value retrieval from the JavaScript objects using the `Object Destructuring` syntax. It is a new syntax introduced in EcmaScript version 6(ES6). It helps to retrieve values from the object property and assign them to variables.

The expression to retrieve the `name` property value from the `student` object using object destructuring is the following,

```js
const {name} = student;
console.log(name); // John Williamson
```
On the left side of the expression, we use the object property key(in this case, it is `name`) and place it inside the `{}`. It also becomes the variable name to hold the property value. We mention the `const`, `let` keywords to define the variable scope. No separate variable declaration is required.

On the right side of the expression, we use the actual object to retrieve the value.

![destructure_2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619319910138/-w4sg_9xU.png)

So, how do we retrieve more than one property value using object destructuring? We keep adding the object keys inside the `{}` on the left side of the expression. In the example below, we retrieve `name`, `age`, and `std` information from the `student` object using object destructuring syntax.

```js
const {name, age, std} = student;
console.log(name, age, std); // John Williamson 9 3
```
Have you noticed, we have saved ourselves from writing a couple of extra lines of code here?

# Add a New Variable with a Default Value
We have seen, object destructuring simplifies the property value retrieval with the new syntax. But it is not limited to just that. We can add a brand new variable while destructuring, optionally with a default value. In the example below, the `meal` variable is non-existent in the `student` object. But we can add it in the object destructuring expression and add a default value to it.

```js
const {name, std, meal='bread'} = student;
console.log(meal); // bread
```
How do you achieve the same otherwise? Here is the alternate code where you need to check a condition and assign.

```js
let meal = student.meal ? student.meal : 'bread';
```
## New Variable with a Computed Value
In the example above, we have created a new variable and assigned a constant value(`bread`). We can also assign a value computed from other destructured variables from the same object.

Here is an example where we have added a new variable called `numberOfSubjects` and assigned a value computed using another property's(`subjects`) value.

```js
const {subjects, numberOfSubjects=subjects.length} = student;
console.log(numberOfSubjects); // 3
``` 

# Add Aliases using Destructuring
We can give an alias name to our destructured variables. It is useful when there are chances of variable name conflicts.

In the example below, we have specified an alias name for the property, `std` as `standard`.

```js
const {std: standard} = student;
console.log(standard); // 3
```
A point to note here. If we try to access the `std` variable after assigning the alias, we will get a `ReferenceError` saying, `std is not defined`. Hence once we create an alias, we can access the property value only using the alias name.

![alias reference error](https://cdn.hashnode.com/res/hashnode/image/upload/v1619326452014/ZogGhzAMM.png?border=1,CCCCCC&auto=compress)

# Nested Object Destructuring
A nested object has one or more property values as objects. The `student` object we are using in this article is a nested object. It has two properties, `address` and `parents` have object values.

```js
const student = {
.....
'parents': {
   'father': 'Brown Williamson',
   'mother': 'Sophia',
   'email': 'john-parents@abcde.com'
 },
 'address': {
   'street': '65/2, brooklyn road',
   'city': 'Carterton',
   'country': 'New Zealand',
   'zip': 5791
 }
.....
}
```
So far, we have seen examples of retrieving non-object key values. We can go deep nested in the hierarchy to retrieve any object key values from any depth using destructuring. In the example below, we have retrieved the `zip` value from the `address` property of the `student` object.

We are already aware of how to retrieve the value of the `address` key,

```js
const {address} = student;
```
Here is the output if we log the `address` variable in the console,

![Logging Address to the console](https://cdn.hashnode.com/res/hashnode/image/upload/v1619327330153/BZhtJ-IcW.png?border=1,CCCCCC&auto=compress)

But we are interested in the `zip` value and we want it in one step. Let's use destructuring,

```js
const {address : {zip}} = student;
console.log(zip); // 5791
```
You can go to any depth like this. You need to always start with the top level and go down in the hierarchy until you reach the value you want to retrieve.

# Destructure to the Function Parameters
We can write precise and smart code using object destructuring and pass as function parameters. Let us understand it with an example. The usual student object is like,

```js
const student = {
 'name': 'John Williamson',
 'age': 9,
 'std': 3,
 'subjects': ['Maths', 'English', 'EVS'],
 'parents': {
   'father': 'Brown Williamson',
   'mother': 'Sophia',
   'email': 'john-parents@abcde.com'
 },
 'address': {
   'street': '65/2, brooklyn road',
   'city': 'Carterton',
   'country': 'New Zealand',
   'zip': 5791
 }
}
```
Let's assume we have a function that sends an email to the student's parent(note, there is an `email` property under the `parents` property). This function also logs a statement for a successful email sent.

So, we can call the function like,

```js
sendEmail(student);
```
We can use destructuring to pass the `email` value to the function definition. There is no need to pass the entire `student` object and then retrieve the required value inside the function.

```js
const sendEmail = ({parents: {email}}) => {
  console.log(`Sent email to ${email}`);
}
``` 
Please note, we have performed the nested object destructuring in the above function to retrieve the `email` value.

# Destructure Function Return Value
In JavaScript, a function may return an object. When we call that function, we may not be interested in the entire object but its specific property values. Here is another opportunity to use object destructuring.

In the example below, the function `getStudent` returns an object,

```js
const getStudent = () => {
 return {
    'name': 'John Williamson',
     'age': 9,
     'std': 3,
     'subjects': ['Maths', 'English', 'EVS'],
     'parents': {
       'father': 'Brown Williamson',
       'mother': 'Sophia',
       'email': 'john-parents@abcde.com'
     },
     'address': {
       'street': '65/2, brooklyn road',
       'city': 'Carterton',
       'country': 'New Zealand',
       'zip': 5791
     }
 }
}
```
We are only interested in name and subject key values. We can retrieve them using the destructuring expression,

```js
const { name, subjects } = getStudent();
console.log(name, subjects);
```
The output,

![Object Destructuring Function Return](https://cdn.hashnode.com/res/hashnode/image/upload/v1619329489632/vGdkB3UQQ.png?border=1,CCCCCC&auto=compress)

# Destructure within the Loop
Object destructuring comes in handy when we need the object key values within a loop. We can use destructuring with the `for-of` loop using a simple syntax. Let's take an array of students. To keep it simple, each of the student objects has only two properties, name and grade.

```js
const students = [
    {
        'name': 'William',
        'grade': 'A'
    },
    {
        'name': 'Tom',
        'grade': 'A+'
    },
    {
        'name': 'Bob',
        'grade': 'B'
    }
];
```
Now, we will use the `for-of` loop to iterate over the `students` array and retrieve the values from each of the student objects. To do that, we can use object destructuring as,

```js
for(let {name, grade} of students){
 console.log(`${name} has got the grade ${grade}`);
}
```
The output,

![Students Grade](https://cdn.hashnode.com/res/hashnode/image/upload/v1619329935314/ZR9Eo_qrs.png?border=1,CCCCCC&auto=compress)

# Destructuring using Dynamic Name Property
In many cases, you may not know the key of an object's property in advance. You may only know it at the run time of the code execution. In those cases, you can not hard-code the key name to retrieve the value using object destructuring.

For example, let us take a function `getStudentInfo` that takes a key as a parameter and returns the corresponding value from the object. 

```js
getStudentInfo('name'); // Returns, John Williamson
getStudentInfo('age'); // Returns, 9
```
The parameter passed to the function `getStudentInfo` is dynamic. Hence to use `object destructuring` with the dynamic keys, we need to enclose the key with a pair of square brackets(`[...]`).

```js
const getStudentInfo = key => {
  const {[key]: value} = student;
  return value;
}
```
Omitting the square brackets in the above code would result in the `undefined` value.

# A Few Tips about Object Destructuring
Object destructuring is an exciting inclusion to the JavaScript programming language. As you have seen so far, there are many possibilities to use in our day-to-day programming using JavaScript. Here are a few tips you may find helpful.

- The `let`, `const` keywords have a significant role in the object destructuring syntax. Omitting them in the code syntax will end up in error, `Uncaught SyntaxError: Unexpected token '='`.

 ```js
 // Don't do this
 {name} = student; // Uncaught SyntaxError: Unexpected token '='
 ```

 Even if you declare the variable in advance and try to use it later in the destructuring syntax, it will result in a similar error.

 ```js
 let name;
 {name} = student; // Uncaught SyntaxError: Unexpected token '='
 ```

 In case you have to omit the `let`, `const` keywords, you have to put the destructuring expression inside the parenthesis (`(...)`).

 ```js
 let name;
 ({ name  } = student);
 console.log(name); // John Williamson
 ```
- Object destructuring syntax may be a bit hard to remember. It is okay if you do not remember it ultimately. It is usual. You can refer to any guide like this one to get the syntax and use it.

<HR />
I hope you enjoyed this article or found it helpful. Let's connect. You can find me on  [Twitter(@tapasadhikary)](https://twitter.com/tapasadhikary) sharing thoughts, tips, and code practices.

<br />
👋 Do you have further questions on `Object Destructuring`? Are you looking for a 1-1 session on this topic? You can reach out to me for a chat or call. Please check my availability on [Hire the Author](https://www.hiretheauthor.com/tapasadhikary).

You may also like,
- [5 useful tips about the JavaScript array sort method](https://blog.greenroots.info/5-useful-tips-about-the-javascript-array-sort-method-ckfs2cifq00eju9s17dfy3jq8)
- [Explain Me Like I am Five What are ES6 Symbols?](https://blog.greenroots.info/explain-me-like-i-am-five-what-are-es6-symbols-ckeuz5sb8001qafs14of305dw)
- [The definitive guide to JavaScript Debugging [2021 Edition]](https://blog.greenroots.info/a-practical-guide-to-web-app-performance-debugging-ckkrw0x8b05pciis1h6em0sb1)
- [A practical guide to web app performance debugging](https://blog.greenroots.info/a-practical-guide-to-web-app-performance-debugging-ckkrw0x8b05pciis1h6em0sb1)

P.S. I love Coffee ☕. <a class="bymecofee" href="https://www.buymeacoffee.com/greenroots" target="_blank"><img width="200px" src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coff"  /></a>