Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Rather than getting a whole data, with destructuring we can only retrieve the values we want.

Destructuring arrays

We have a function groceries which returns us our list of items that we wish to buy next time we go to a supermarket.

The data that groceries function returns is as follows; [bread, apples, cheese]

In a traditional sense we would get a reference to each item in this way;

1const groceriesList = groceries();
2const bread = groceriesList[0];
3const apples = groceriesList[1];
4const cheese = groceriesList[2];

Destructuring allows us to achieve this in an elegant and simple way

1const [bread, apples, cheese] = groceries();

If you also want a reference to the groceries list all you need to do is;

1const [bread, apples, cheese] = (groceriesList = groceries());

But, what happens if groceries returns us an array with four values?

Simply, we would only get the first three values without touching the fourth value.

What happens when we want to retrieve three values but groceries function returns two values?

Let's say the array doesn't have cheese value and we want to reference to this value with the cheese variable.

The code would not break and the cheese variable will simply be undefined

Undefined values

Another case is when a value is undefined.

Imperatively if a value can be undefined and we want a default value to it when it's undefined.

We would do;

1const name = names[0] !== undefined ? names[0] : "unregistered";

Declaratively, using destructuring we do;

1const [name = "unregistered"] = names;

What if we want to get the first three into their own variables and the rest into one variable?

In order to achieve this we use the spread operator.

1const [
2 bread,
3 apples,
4 cheese
5 // gather the rest of them and put them into variable others
6 ...others
7 ] = groceries()

Variable swapping with destructuring

Destructuring allows a handy trick for swapping two variables without the need for a temp variable.

1[x, y] = [y, x];

Destructuring function paramaters

You can destructure an array which is a parameter to a function

1const arr = [1, 2, 3, 4, 5];
2const firstThree = ([one = 10, two, three]) => {
3 // do something

The parameter 10 has a default value of 10 if it receives undefined

Destructuring nested arrays

We can destructure nested array using another pair of brackets inside our brackets

1const data = [1,[2,3],4]
2const [
3 one,
4 // fallback to an empty array if undefined
5 [two, three] = [],
6 four