Object Destructuring in JavaScript
Tags: javascript, beginners, destructuring, tutorial
Published: 2024-02-27 14:14:48

Last week we talked about array destructuring [here](https://dev.to/baroblesvi/destructuring-arrays-in-javascript-4c5n). Now let's finally understand object destructuring!

Contents:

  * [Basic Syntax](#basic-syntax)
  * [Renaming Properties](#rename)
  * [Default Values](#default-values)
  * [Renaming and Default Values](#renaming-default)
  * [Nested Objects](#nested-objects)
  * [Mutating Variables](#mutating)

### Basic Syntax <a name="basic-syntax"></a>

Destructuring is a simple way to extract data from arrays or objects into separate variables. Now, let's  delve into the workings of object destructuring.

Consider this object as an example:

```javascript
const user = {
  userName: 'Ada',
  age: 28,
  city: 'São Paulo'
};
```

Now let's extract the `data` for `city` and age using destructuring:
```javascript
const { city, age } = user;
```
Here, we've created two variables: `city` and `age`. These variables will hold the values corresponding to properties of the same names found in the `user` object.

And now we can work independently with this information:

```javascript
console.log(city); // output: 'São Paulo'
console.log(age); // output: 28 
```
Some important details should be noted:

1. Note that the `userName` property was omitted in the destructuring. Unlike array destructuring, it's not necessary to manually skip properties.

2. The order of the variables listed in the destructuring doesn't matter. You'll see that I placed `city` before `age`, which won't result in an error. This is because in objects, properties do not follow a fixed order!

3. Variable names can be changed while destructuring! For this, see below:

### Renaming Properties <a name="rename"></a>

We can easily change the names of the properties extracted from the object at the same time as the destructuring assignment. This feature is particularly useful when you want to avoid naming conflicts:

```javascript
const { city: c, age: a } = user;

console.log(c); // output: 'São Paulo'
console.log(a); // output: 28 
```

### Default Values <a name="default-values"></a>

It's possible that some of the values extracted may be `undefined`, which can be a source of bugs in your code. We can avoid this quite easily.

Let's assume we want to extract a `nationality` property, which hasn't been defined. To avoid the variable being assigned `undefined`, we can assign it a default value, like this:

```javascript
const { city, age, nationality = 'Brazilian' } = user;
```

### Renaming and Default Values  <a name="renaming-default"></a>

It is possible to combine the above syntaxes. So we can combine the process of renaming variables and setting default values simultaneously:

```javascript
const { 
  city: c = 'Belo Horizonte',
  age: a = 18,
  nationality: n = 'Brazilian'
} = user;
```

And in the case of the `user` object, the output will now be this:

```javascript
console.log(c); // output: 'São Paulo'
console.log(a); // output: 28 
console.log(n); // output: 'Brazilian'
```
Note that the default value will only be applied to `n`, since the other values were already defined.

### Nested Objects <a name="nested-objects"></a>

If the object in question contains another object within it, it's also possible to destructure the nested object. Let's add `grades` for subjects to the `user` object:

```javascript
const user = {
  userName: 'Ada',
  age: 28,
  city: 'São Paulo',
  grades: {
    math: 9.5,
    portuguese: 9.2,
    chemistry: 10,
    history: 7.5,
    geography: 7.8,
  }
};
```

To work separately with the grades, we can destructure like this:

```javascript
const {
  grades: {
    math, 
    portuguese, 
    chemistry, 
    history, 
    geography 
  } 
} = user;
```

And now, the values can be accessed separately:

```javascript
console.log(math) // output: 9.5
console.log(portuguese) // output: 9.2
console.log(chemistry) // output: 10
console.log(history) // output: 7.5
console.log(geography) // output: 7.8
```


### Mutating Variables <a name="mutating"></a>

Next, let's explore the scenario where variables are already declared and initialized, such as `a` and `b` below:

```javascript
let a = 55;
let b = 77

const object = {
  a: 41,
  b: 27,
  c: 14
};
```

How can we assign `a` and `b` the values contained in the object? We can't write `let {a, b} = object` or `const {a, b} = object`, since we would be redeclaring the variables. But we also can't write `{a, b} = object`, as JavaScript interprets any line starting with curly braces `{}` as a block of code, resulting in a syntax error in the code.

The solution is to wrap the code using parentheses:

```javascript
({a, b} = object);

console.log(a); // output: 41
console.log(b); // output: 27
```

This way, JavaScript will understand it as destructuring and not a block of code.

Thank you for making it this far! =)

Questions, comments, suggestions? Comment below!