> ## Content Index
> Fetch the complete content index at: https://mindsers.blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Destructuring in Javascript
- URL: https://mindsers.blog/en/post/destructuring-javascript/
- Published: 2019-04-03T04:00:00.000Z
- Updated: 2023-11-20T07:30:34.000Z
- Author: Nathanaël Cherrier
- Tags: javascript, coding-tech, es6, rest, spread, decomposition, #lang-en

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.

```js
let [ valeur1, valeur2 ] = tableau
let { valeur1, valeur2 } = objet

```

The syntax is different whether 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.

```js
let args = ['fruits', 'pomme', 'poire', 'abricot']
let type = args[0]
let firstEl = args[1]
let secondEl = args[2]
let thirdEl = args[3]

```

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

```js
let args = ['fruits', 'pomme', 'poire', 'abricot']
let [type, firstEl, secondEl, thirdEl] = args

```

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 coded the same feature without destructuring.

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

```js
let args = ['fruits', 'pomme', 'poire', 'abricot']
let [type,, secondEl] = args

```

You just have to add a comma 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.

```js
let args = []
let [type = 'legume', firstEl = 'salade'] = args

```

As `args` is empty, `type` will have “legume” 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.

```js
let args = ['fruits', 'pomme', 'poire', 'abricot']
let [type, ...elements] = args

```

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 parameter. [If you want to learn more about rest parameter, you can read this post (in French).](https://mindsers.blog/fr/post/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.

```js
let valA = 'coucou'
let valB = 'byebye'
[valA, valB] = [valB, valA]

```

Logically, `valA` will have “bye bye” as a value and `valB` will have “coucou”.

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

```js
let [max, min] = getMaxAndMin([3, 34, 2, 5, 6, 22, 33, 1])

```

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.

```js
function firstIsTrue([ first = false ]) {
  return first === true
}

```

`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

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

let { title } = objet

```

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

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

let { visible = false } = objet

```

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

**Example :** Using another 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.

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 `{ visible: visible }` is equal`{ visible }`.

**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 parameters 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 user's 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 resources to go deeper :

- [Understanding fetch, jQuery.ajax substitute](https://mindsers.blog/fr/post/fetch-fin-jquery-ajax/) (French)
- [Understanding the destructuring operator and rest parameter in JavaScript](https://mindsers.blog/fr/post/rest-parameter-et-spread-operator-en-javascript/) (French)
- [Understanding decoupling](https://mindsers.blog/post/destructuring-javascript/)