JS Bits - Destructuring arrays in JavaScript!

JS Bits - Destructuring arrays in JavaScript!

Destructuring

Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. (dev.to/sarah_chima/destructuring-assignment..)

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;

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

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

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

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

const [
    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;

const name = names[0] !== undefined ? names[0] : 'unregistered'

Declaratively, using destructuring we do;

const [
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.

const [
    bread,
    apples,
    cheese
    // get the first three as normal then
    ...others // gather the rest of them and put them into variable others
] = groceries()

Variable swapping with destructuring

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

[x,y] = [y,x]

Destructuring function paramaters

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

const arr = [1,2,3,4,5]
const firstThree = ([one = 10, two, three]) => {
    // 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

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

]

Thank you for reading! If you have any questions please let me know here!