Array destructuring in Javascript
Tags: javascript, es6, destructuring, arrays
Published: 2021-01-23 19:43:04

In this article **you are going to learn all about array destructuring** in Javascript and **some cool tricks** you can perform using it, like swapping values of variables, returning multiple values from a function, copying an array, etc.

Essentially, we use **destructuring** in Javascript to unpack data from more complex data structures like arrays and objects into individual variables of choice, without having to repeat ourselves too much.

Check my video on this topic:

{% youtube PVVDTq1W0rI %}

Otherwise, keep reading to know more and learn all about **destructuring arrays**.

## Basics
When we declare and initialize a variable, essentially we _pack_ the data into it. For example, let's suppose we create an array:

```jsx
const numbers = [10, 20, 30, 40];
```

We can say we have _packed_ the numbers 10, ..., 40 into the `numbers` variable.

Now, instead of doing the following to store individual elements of this array into variables and repeating ourselves too much:

```jsx
const a = numbers[0];
const b = numbers[1];
/// ...
```

We can use **destructuring** to _unpack_ this data:

```jsx
const [a, b, c, d] = numbers;
console.log(a); // 10
console.log(d); // 40
```

Keep in mind that it's not needed to declare the variables in the same line as destructuring:

```jsx
const a, b, c, d, e;

[a, b, c, d, e] = numbers;
console.log(a); // 10
console.log(e); // 50
```

If the number of values we are destructuring is less than the total number of elements in the array, we are going to destructure only the same number of elements from the beginning of the array:

```jsx
const [a, c] = numbers;
console.log(a); // 10
console.log(c); // 20
```

But what if we try to destructure more values than there exist in the array? In that case the extra variables that map to non-existing array elements will have the value of `undefined`:

```jsx
const [a, b, c, d, e, f] = numbers;
console.log(e); // undefined
console.log(f); // undefined
```

### Default values for undefined elements
In the previous example we were trying to destructure variables that didn't exist in the array `numbers`. We can choose what would be the **default** values assigned to those variables in that case by using the `=` operator:

```jsx
const [a, b, c, d, e = 0, f = 0] = numbers;
console.log(e); // 0
console.log(f); // 0
```

### Ignoring elements
We can ignore some elements in sequence, if we don't want to destructure them:

```jsx
const [a, , c, d, e, f] = numbers;
console.log(a); // 10
console.log(c); // 30
```

That being said, we can also ignore multiple values in a row like `[a,,,d,e,f] = numbers`, but the code gets quite unreadable that way, so try to avoid using it. As a matter of fact, there is already an ESLint rule out there that prevents ignoring more consecutive values (for more check [eslint-plugin-unicorn](https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/no-unreadable-array-destructuring.md))

### Iterables
Since destructuring is just syntax sugar for iteration, it can be performed on any iterable, not just arrays. So, for example, a string is an iterable, so we can do this:

```jsx
const [a, b, c, d] = "cool";
console.log(a, b, c, d); // c o o l
```

### Nested array destructuring
We can also destructure nested arrays, i.e. arrays within arrays

```jsx
const destination = ['Paris', [48.8566, 2.3522]];

const [city, [latitude, longitude]] = destination;
console.log(latitude, longitude); // 48.8566 2.3522
```

## Tricks using array destructuring
OK, so now that we got the basics down, let's check out some tricks we can perform using destructuring in Javascript.

### Swapping variables
Let's say we have variables `a` and `b`, and we want to swap their values so that `a` contains the value of `b`, and `b` contains the value of `a`. We can use array destructuring syntax to do that:

```jsx
const a = 1;
const b = 2;
[b, a] = [a, b];

console.log(a); // 2
console.log(b); // 1
```

### Multiple function return values
If we ever want to return more than one value from a function, and capture those values where the function is called, again we can use array destructuring to achieve this:

```jsx
function getPerson() {
	const name = "Johnny Knoxville";
	const age = 30;
	const phone = "123456"
	
	return [name, age, phone];
}

// ... somewhere else we call getPerson()
const [personName, personAge, personPhone] = getPerson();

console.log(personName); // "Johnny Knoxville"
console.log(personAge); // 30
console.log(personPhone); // 123456
```

### Capturing the rest of an array as another array
When destructuring the first few values of an array, we may want to store the values **that we haven't destructured** into a new array.

To achieve this, we can use the _spread_ operator `...` to capture the rest of the elements into the new array:

```jsx
const numbers = [1, 2, 3, 4, 5, 6, 7];
const [a, b, ...rest] = numbers;
console.log(rest); // [3, 4, 5, 6, 7];
```

An important point to note here is that the `...rest` has to always be at the end of the array we use for destructuring, otherwise an error will be thrown.
Another important thing about this to remember is that after this runs, the `rest` variable will hold an array which is a completely different array in memory than the `numbers` array, i.e. the remaining values from the `numbers` array **are copied into a new array** stored in the `rest` variable.

Because of this, we can utilise this as a trick **to clone an array**:

```jsx
const numbers = [1, 2, 3, 4, 5, 6, 7];
const [...numbersCopy] = numbers;
console.log(numbersCopy); // [1, 2, 3, 4, 5, 6, 7]

numbersCopy[0] = 999;

// The original array stays the same
console.log(numbers); // [1, 2, 3, 4, 5, 6, 7]
```

## Conclusion
That’s it when it comes to destructuring arrays in Javascript. Hope you can utilize the info presented here and take one more step towards writing [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) code.

We can use a similar syntax to destructure Javascript objects as well, but to keep this article focused, I’m leaving that as a follow-up article which I plan to publish very soon.