Array Destructuring in JavaScript

JavaScript allows us to destructure an object into individual variables check this tip for details.

We can do the same thing with arrays, even though they are ordered and lack key-value pairs.

Object Destructuring Example

As a refresher on object destructuring, say we have an object representing a product with properties such as SKU, name, price, and inStock status:


const product = {
sku: "198273902183",
name: "landhauler wheelbarrow 400lbs",
price: 199.99,
inStock: false,
};

We can extract the name and price properties into their own variables very simply:


let { name, price } = product;

If we run our code, we'll have name and price as standalone variables. Check out this tip for more

Array Destructuring

Just as we can destructure an object into individual standalone variables, we can do the same with arrays. However, the key difference is that arrays are ordered, and we don't have key-value pairs as we do with objects

Array destructuring is slightly different because we can't extract values based on their property names. Instead, we do it based on their position in the array.

We have an array results representing the order in which employees finished a 100-meter sprint:


const results = ["Elton", "Primrose", "Bennifer", "Tim", "Jim", "Bim"];

In this array, 'Elton' finished first, 'Primrose' second, and so on.

To destructure values based on their order, we use the square brackets (or the array brackets) on the left-hand side of the equal sign and set that equal to the array.

Destructuring arrays allows us to assign variables to elements in an array without having to match the variable names with any specific element in the array. All that matters is the order or position of the elements in the array:


const [gold, silver, bronze] = results;

In this case, the variable gold will be equal to 'Elton', silver will be equal to 'Primrose', and bronze will be equal to 'Bennifer'.

It's important to note that the order matters here. If we switch the order of the variables, the assignments will also switch. For example, if we switch silver and gold:


const [silver, gold, bronze] = results;

Now silver will be equal to 'Elton', and gold will be equal to 'Primrose'.

Remember that this operation does not mutate or change the array in any way. It simply assigns values from the array to variables.

If we want to collect any remaining unassigned values into a new array, we can use the ... rest operator:


const [gold, silver, bronze, ...others] = results;

Now, 'Tim', 'Amy', and 'Jake' will be collected into the others array.

Array Destructuring in React

Array destructuring might not seem as helpful as object destructuring at first, but it's commonly used in the world of React, particularly with the useState hook.

If you're not familiar with React or the useState hook, don't worry. The important thing to note here is that useState always returns an array with two elements. The first element is a value, and the second element is a function to update that value. By using array destructuring, we can directly extract these two elements into their own variables:


const [dice, setDice] = useState(getRolls(numDice));

In this case, we're extracting the first element into a variable called dice and the second element into a function called setDice. The order matters here: dice corresponds to the first element of the array, and setDice corresponds to the second element.

Here's an even simpler React component following the same pattern:


const [count, setCount] = useState(0);

Again, useState returns an array, and we're using array destructuring to extract the elements of that array into their own variables.

Array destructuring is a useful tool to be aware of, especially when working with React.

Transcript

00:00 In this video, we're going to talk about array destructuring. Now, if you're not familiar with object destructuring, I would check out the video I did on that first, mostly because object destructuring is far more common in the real world of JavaScript and it's a better place to start. So if you're familiar with that concept of destructuring values out of

00:19 an object into individual standalone variables, we have a similar concept that we can do with arrays. The key difference here, of course, is that arrays are ordered. We don't really have key value pairs like we do with an object. I can destructure name out of here or price very simply. I could do const and then curly braces,

00:38 name, price. This is an object representing a product. There's a skew, a name, a price, and in stock. I'm extracting the values of name and price into their own variables. If I run my code, I have name and I have price. Now, with an array,

00:56 it's a little bit different because we can't call out variables based on names here, or the keys, but rather we do it based on their position in the array. So this is the results, let's say, of an inter-office race, a 100-meter sprint out in the field in front of the office.

01:15 So it's in order. This person, Elton, finished first. Primrose was second. Benefer was third. Tim, Jim, and Bim round up the rest of the pack. What I can do to destructure values out based on the order is use the square brackets or the array brackets on the left-hand side of the equal sign. Set that equal to the array.

01:33 In this case, it's called results. Then I can name variables whatever I want. The names don't have to match anything in here. All that matters is the position or the order. So I could call, maybe I'll give out metal awards, gold, silver, and bronze. So gold, if I just did this,

01:51 will make me a variable called gold equal to the first value in the array, Elton. Now, if I add a second variable in here, silver, I now have gold, not golf, I have gold set to Elton, and then I have silver set to Primrose.

02:10 It's based on the order. So if I switch the order here, silver and then gold, now silver will be set to the first value in the array of Elton and gold will be set to the second which doesn't really make sense if this is the winner and this is second place. Just like with object destructuring,

02:29 this does not change or mutate the array in any way. It's simply referencing values from that array, putting them in variables. So let's fix this. Let's go back to gold, silver, and then bronze. So bronze here should be equal to Bennifer.

02:46 Silver is the second element of Primrose and gold would be the first of Elton. I could keep chaining on as many different variables as I want. If I have a fourth place, I could just call the variable fourth and that would be equal to Tim. But another thing I can do is actually collect any remaining uncaptured values.

03:06 So after the first three, Elton, Primrose, and Bennifer, collect all the others using dot, dot, dot. Into an array, we'll call this others. This will make me a variable called others that holds everything else in the array. However many things are in here,

03:22 doesn't really matter, they will all be collected into others. As you see over here, Tim, Jim, Bim, ASDAS, ASDASD. But the first three values, Elton, Primrose, and Bennifer are extracted into their own variable.

03:40 So it's not as useful in my experience as object destructuring, but there's at least one place where it comes up all the time in the world of React. This is a simple React component and it doesn't matter if you're not comfortable or even familiar with React. There's a very useful hook, basically a function built into React that we use a lot called useState.

03:59 The way that useState works, I'm calling it right here, is that it always returns an array. This array always has the same shape. The first element is a value, the second element is a function. So when we call useState, we often, almost 100 percent of the time,

04:17 we'll use array destructuring to get those two things out. In this case, I'm extracting a variable that I'm calling dice, and then a function called setDice, and it's all based on the order. We have array destructuring here. So take the first thing that we get back from this array, and it always returns an array with two elements.

04:36 Take the first thing, call it dice. Take the second thing and call it setDice. Here's an even simpler React component, same exact pattern. We call this function useState. Again, it doesn't matter if you don't know what it does, and it returns an array. We destructure that array so that we get two pieces out. The first piece always is a value,

04:56 the second piece always is a function, and conventionally, we'll name them num and setNum, dice and setDice, color and setColor, whatever the values are, it doesn't matter. What matters is that we're using array destructuring here to get the first element from the array and stick it in a variable. Get the second element and stick that in a separate variable.

05:15 And that is the basic concept of array destructuring. We use the order of the array to destructure values, to extract them out into whatever variable names we want.

More Tips