DEV Community

Nathanaël CHERRIER
Nathanaël CHERRIER

Posted on • Originally published at mindsers.blog on

Destructuring in 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.

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

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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

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

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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).

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.

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

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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

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

let { title } = objet

Enter fullscreen mode Exit fullscreen mode

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

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

let { visible = false } = objet

Enter fullscreen mode Exit fullscreen mode

You only want visibility and a false by default.

Example : Using an other name for a key

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

let { content: article } = objet

Enter fullscreen mode Exit fullscreen mode

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

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

let { visible: isVisible = false } = objet

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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 :

Top comments (0)