Destructuring in Javascript
Tags: javascript, es6, rest, typescript
Published: 2019-04-04 08:39:14

---
title: Destructuring in Javascript
published: true
tags: javascript,es6,rest,typescript
canonical_url: https://mindsers.blog/en/destructuring-javascript/
---

Destructuring applies to arrays and objects. It consists in breaking down complex structures (array, object) to extract the values we are interested in. Those manipulations make the code simpler and easier to read.

<!--kg-card-begin: markdown-->
```js
let [valeur1, valeur2] = tableau
let { valeur1, valeur2 } = objet

```
<!--kg-card-end: markdown-->

The syntax is different wether it is an array or an object.

## Breaking arrays down

A concrete example of breaking arrays down is when you want to get values from an array.

<!--kg-card-begin: markdown-->
```js
let args = ['fruits', 'pomme', 'poire', 'abricot']
let type = args[0]
let firstEl = args[1]
let secondEl = args[2]
let thirdEl = args[3]

```
<!--kg-card-end: markdown-->

Without destructuring, here is how we can get the values from an array to use them.

<!--kg-card-begin: markdown-->
```js
let args = ['fruits', 'pomme', 'poire', 'abricot']
let [type, firstEl, secondEl, thirdEl] = args

```
<!--kg-card-end: markdown-->

Same thing with destructuring.

The two bits of code are similar, the result is the same. In each case, the variable `type`, `firstEl`, `secondEl`, `thirdEl` are created.

If we stop here, this syntax has not a great interest except sparing us three lines of code. But destructuring has a lot more in store that will make you time efficient.

We will not compare with examples without destructuring each time but try to think of how you would have code the same feature without destructuring.

**Example :** If I only want to get the type and the second element back.

<!--kg-card-begin: markdown-->
```js
let args = ['fruits', 'pomme', 'poire', 'abricot']
let [type,, secondEl] = args

```
<!--kg-card-end: markdown-->

You just have to add a coma between `args[0]` and `args[2]` without specifying the variable name of `args[1]`.

**Example :** If `args` is empty, my variables `type` and `secondEl` will be created but will have `undefined` as value. To be able to continue working with it, I would have to test my variables. But I can also assign them default values.

<!--kg-card-begin: markdown-->
```js
let args = []
let [type = 'legume', firstEl = 'salade'] = args

```
<!--kg-card-end: markdown-->

As `args` is empty, `type` will have "légume" as value and `firstEl` will have "salade" as value.

**Example :**  If I want to get back to the type of my elements in a variable, but it would be easier for me to have the list of elements in an array to loop on.

<!--kg-card-begin: markdown-->
```js
let args = ['fruits', 'pomme', 'poire', 'abricot']
let [type, ...elements] = args

```
<!--kg-card-end: markdown-->

Here `type` will have "fruits" as value and `elements` will have `['pomme', 'poire', 'abricot']`.

The syntax here is quite particular because it uses what we call a rest paramater. [If you want to learn more about rest paramater, you can read this post (in French).](https://blog.nathanaelcherrier.com/2016/11/09/rest-parameter-et-spread-operator-en-javascript/)

You can also use destructuring in case you would not think about it usually :

**Example :** If I want to swap the values of two variables.

<!--kg-card-begin: markdown-->
```js
let valA = 'coucou'
let valB = 'byebye'
[valA, valB] = [valB, valA]

```
<!--kg-card-end: markdown-->

Logically `valA` will have "byebye" as a value and `valB` will have "coucou".

**Example :** Destructuring can be used to work with functions that return arrays.

<!--kg-card-begin: markdown-->
```js
let [max, min] = getMaxAndMin([3, 34, 2, 5, 6, 22, 33, 1])

```
<!--kg-card-end: markdown-->

The interest here is the readability of the code. Of course, you will need to be sure of the order of the returned values by the used function.

**Example :** It is possible to use destructuring as function parameter.

<!--kg-card-begin: markdown-->
```js
function firstIsTrue([first = false]) {
  return first === true
}

```
<!--kg-card-end: markdown-->

`firstIsTrue()` take an array in parameter. Only the first value will be transmitted to the function and if the array is empty : `first` will have `false` as value.

For the function user, everything is transparent.

## Destructuring objects

Destructuring objects is quite similar to arrays with a few specificities. We will cover that quickly to stop on more interesting notions.

**Example :** Retrieval of one of our keys

<!--kg-card-begin: markdown-->
```js
let objet = {
  slug: 'test'
  title: 'Ceci est un test'
  content: '...'
  visible: true
}

let { title } = objet

```
<!--kg-card-end: markdown-->

Standard example where we only want the title. You will note that we use brackets instead of square brackets when it is an object.

**Example :** Default value

<!--kg-card-begin: markdown-->
```js
let objet = {
  slug: 'test'
  title: 'Ceci est un test'
  content: '...'
  visible: true
}

let { visible = false } = objet

```
<!--kg-card-end: markdown-->

You only want visibility and a `false` by default.

**Example :** Using an other name for a key

```js
let objet = {
  slug: 'test'
  title: 'Ceci est un test'
  content: '...'
  visible: true
}

let { content: article } = objet

```

Here, we only retrieve the key `content` that we are stocking in the `article` variable.


<mark>The real syntax of destructuring is the one used in this example. In other examples, we used a tip from ES2015 that prevent us from writing the same thing twice when possible. Just remind that <code>{ visible: visible }</code> is equal<code>{ visible }</code>.</mark>


**Example :** Accumulation of default value and name changing

```js
let objet = {
  slug: 'test'
  title: 'Ceci est un test'
  content: '...'
  visible: true
}

let { visible: isVisible = false } = objet

```

We retrieve the key `visible` that we are stocking in the variable `isVisible`. This variable will be by default `false`.

**Example :** Using destructuring as function parameter

It is the case in which I use the most destructuring. It saves so much time.

You probably already wrote some function with an `options` parameter that gather all your options in an object.Think about all that wasted time and that number of lines you had to write to test this parameter before even coding business logic.

```js
function test(id, { maxLength = 10, current = 0 } = {})

```

As for destructuring an array, using it in paramaters is absolutely transparent for users but it changes your whole life.

`maxLength` and `current` will never be `undefined`, will always have a value, either the users or the default one. It will lighten your code as you will not be doing `options.maxLength` anymore but just `maxLength` as if it was a simple parameter as `id`.

Only the attributes that you have declared in destructuring will be transmitted to your function. The user can add 15 000 other attributes to `options`, they will not be transmitted. It adds a bit of security to your function too.

## Conclusion

I really hope I convinced you to try it. Destructuring is, for me, one of the biggest ES2015 new feature.

A powerful function to use without moderation to make your code simpler, clearer, beautiful, cleaner... And you know how I like clean code.

Some ressources to go deeper :

- [Understanding `fetch`, `jQuery.ajax` substitute](https://blog.nathanaelcherrier.com/2016/10/26/fetch-fin-jquery-ajax/) (French)
- [Understanding the destructuring operator and rest paramater in Javascript](https://blog.nathanaelcherrier.com/2016/11/09/rest-parameter-et-spread-operator-en-javascript/) (French)
- [Understanding decoupling](https://blog.nathanaelcherrier.com/2016/08/30/decouplez-votre-code/) (French)