How to destructure arrays in JavaScript?

Learn JS: Destructuring, Lesson 6.

Let's start with a simple array:

const users = ["robot", "person", "dog"]

We can access its elements with a [] for example

const robot = users[0];
const person = users[1];
const dog = users[2];

So now the same thing using the destructuring assignment.

const [ robotUser, person, dog ] = users;
console.log(robotUser); // "robot"
console.log(personUser); // "person"
console.log(dogUser); // "dog"

Of course, you're free to give them any names and ignore elements at your will.

const [ firstUser, secondUser ] = users;
console.log(firstUser); // "robot"
console.log(secondUser); // "person"

It looks a little weirder when you want to ignore elements from the front of the array.

const [ , , thirdUser ] = users;
console.log(thirdUser); // "person"

But you can think of it as destructuring and not giving names (ignoring) the first elements.

const [ /*ignored*/, /*ignored*/, thirdUser ] = users;
console.log(thirdUser); // "person"

Accessing elements that don't exist #

const [ whatWillIBe ] = [];
console.log(whatWillIBe); // undefined

If you try to access an element in the array that doesn't exist, you will get undefined. It's much more convenient than an exception, but now you have to remember about it.

Default value #

const [ usesDefaultValue = 42 ] = [];
console.log(usesDefaultValue); // 42

(It works similar to assigning default values when destructuring objects)

Destructuring nested arrays #

const users = [["robot", 21], ["person", 34]];

How can we access "robot" element?

const robotName = users[0][0];
console.log(robotName); // "robot"

But the destructuring assignment lets you show the structure of what you want to get.

const [[userName]] = users;
console.log(userName); // "robot"

Accessing nested arrays that don't exist #

try{
const [ [whatWillIBe = 42] ] = [];
}catch(e){
console.log(e)
}
// TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

(Click here if you want to learn how to solve the same problem when destructuring objects.)

If you don't like the idea of adding a try-catch around array destructuring, then you can fix it by adding a default value.

Default value #

const [ [whatWillIBe = 42] = [] ] = [];
console.log(whatWillIBe); // 42

Notice the difference of = [] default value for the nested array:

- const [ [whatWillIBe = 42]      ] = [];
+ const [ [whatWillIBe = 42] = [] ] = [];
const [ usesDefaultValue = 42 ] = [];
console.log(usesDefaultValue); // 42

⮕ See the next lesson to learn how to destructure mixed arrays and objects in JavaScript.

(⬅ If you want to know how to destructure deeply nested objects then read the previous lesson)



Share on Hacker News
Share on LinkedIn


← Home