Photo: Unsplash - Markus Spiske
Array destructuring allows you to define variables based on the position of elements in an array. A simple example is:
To destructure array values you will see that the variables are defined by declaring them in a set of square brackets. They are defined in the order they will be mapped to against the array elements. If the variables do not already exist then you need to prefix the declaration with a let or const. As the position is used to destructure the values from the array you need to handle the position of values you do not want. You will see there is an empty space declared in the a,e and g destructuring.
If you are interested in the first couple of elements in the array then you can apply a “rest” pattern and combine the remaining elements into a single variable. This is achieved by prefixing the final variable declared with three periods as shown in the example below:
You can us this array destructuring approach with iterables as shown below:
Destructuring objects works in a near-identical manner to what we have seen above. Instead of a variable being bound on position, they are bound to object properties as shown below:
An even clearer approach is to use the provided shortcut which works if you name the variables the same of the properties such as:
You will notice that instead of square brackets, object destruction used curly brackets to surround the variable declaration.
In order to deconstruct more complex objects such as the address data in the person object you can nest the declaration of variables in line with the structure of the object. You prefix each block of variable destructuring with the name of the parent property and surround their child declarations with further curly brackets as shown below:
You can nest your destucturing of the data as deeply as you want by continuing the pattern as shown here:
If you try to destructure array elements or object properties that don’t exist your variable will be set to undefined as shown below:
If you are unsure of the properties you are destructuring you can set default values when declaring the variables such as:
Hopefully you can see the benefit of destructuring and how it reduces the number of variable declarations you make to retrieve data from objects and arrays. You can use the syntax in a few ways other than just variable declaration.
You can define a function to accept a single object as a parameter and use the destructuring syntax to pull the actually values from the object that you need such as:
You can also use the syntax to handle returning multiple values from a function such as: