Arrays and Object Destructuring in Javascript
Tags: javascript, react, programming, tutorial
Published: 2023-03-15 16:36:04

I wrote this article for baddies like me who've used destructuring many times in javascript without really understanding its ins and outs. Destructuring is a cool feature that was introduced in ES6/ES2015, I believe to make our lives as developers easy. 

As a JavaScript developer, you're probably familiar with the concept of objects and arrays. Objects and arrays are great for storing and manipulating data in JavaScript. However, sometimes you might find yourself in a situation where you only need a few specific values from an object or array. This is where destructuring comes in handy. 

With destructuring, unpacking data from objects and arrays is done with ease, speed and efficiency. Let's dive in!



## What is Destructuring Assignment

According to Mozilla,  "_The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables._” 

It is simply a way to extract specific data/values from objects or arrays and assign them to variables. It's a shorthand way of assigning values to variables and can help make code more readable and concise. 

## Benefit of Destructuring Assignment

- Destructuring allows you to extract values from objects or arrays in a concise and readable way. Instead of accessing each property or element individually, you can extract all the values you need in a single statement.

- With destructuring you get to extract specific values from objects or arrays, making your code more flexible. You can extract only the properties or elements you need, and ignore the rest.

- Destructuring allows you to avoid repetition in your code. If you need to access the same property or element multiple times, you can extract it to a variable using destructuring, and then reference the variable instead of repeating the same code.

- Destructuring is easy to use with functions particularly when working with functions that take objects or arrays as arguments. By destructuring the arguments, you can easily access the values you need without having to reference the original object or array.

- Destructuring allows you to specify default values for properties or elements that may not exist or may be undefined. This can help prevent errors and simplify your code by avoiding the need for additional checks and conditionals.

## Why Destructuring

**<u>Extracting Data from Arrays</u>**

Before ES6/ES2015 extracting data from an array was done this way: 

```
let numbers = [‘1’,’2’,’3’,’4’,’5,’6’];
let secondNumber = numbers[1];
let lastNumber = numbers[numbers - 1] 

console.log(secondNumber); //2
console.log(lastNumber); //6

```

This becomes repetitive if we have to do this over and over again.  

With ES6/ES2015

```
let numbers = [‘1’,’2’,’3’,’4’,’5’,’6’];
let [firstNumber, secondNumber] = numbers; 

console.log(firstNumber); //1
console.log(secondNumber); //2
```
It is more concise: 

```
let [firstNumber, secondNumber] = [‘1’,’2’,’3’,’4’,’5’,’6’];

console.log(firstNumber); //1
console.log(secondNumber); //2
```

Has the same result. 

Variables can be declared before they get assigned

```
let firstNumber, secondNumber, thirdNumber;
let [firstNumber, secondNumber, thirdNumber] = [‘1’,’2’,’3’,’4’,’5’,’6’];

console.log(firstNumber);//’1’
console.log(secondNumber);//’2’
console.log(thirdNumber);//’3’
```

In the code above you will notice that the variables are set from left to right so – the first variable gets the first item in the array, the second variable gets the second item in the array and so on… 

**Values can be skipped in arrays**

It is possible to skip values in arrays using a comma (,). You can add a comma separator for each value you want to skip in the array. For example: 

```
let [firstNumber,,thirdNumber,,] = [‘1’,’2’,’3’,’4’,’5’,’6’];

console.log(firstNumber);//’1’
console.log(thirdNumber);//’3’
```

If you want to skip all the items in the array, do this – 

```
let [,,,,,,] = [‘1’,’2’,’3’,’4’,’5’,’6’];
```

**Using the spread syntax to assign the rest of an array**

The spread syntax allows an iterable object such as strings or arrays to be expanded into individual elements.

In some cases where we want to assign some of the array to variables and the rest of the items in an array to a particular variable, we would do this – 

```
let [firstNumber, …anotherNumber] = [‘1’,’2’,’3’,’4’,’5’,’6’];

console.log(firstNumber);//’1’
console.log(anotherNumber);//[’2’,’3’,’4’,’5’,’6]
```

With this you can unpack and assign the remaining part of an array to a variable.

**Default Values in Arrays**

Sometimes, the array that you're destructuring might not have a value that you're trying to extract. In such cases, you can provide a default value. For example, consider the following:

```
let [firstNumber = ‘4’,secondNumber = ‘2’] = [‘1’];


console.log(firstNumber);// ’1’
console.log(secondNumber);// ’2’
```

secondNumber is not defined in the array so it falls back to 2

```
let numbers2 = [1, 2];

const [x, y, z = 3] = numbers2;

console.log(x); // Output: 1
console.log(y); // Output: 2
console.log(z); // Output: 3
```

In this example, we're trying to extract three values from the numbers2 array, but it only has two elements. Instead of throwing an error, we can specify a default value for z using the (=) operator.

**Swapping values using array destructuring assignment** 

We can also use array destructuring to swap variable values without needing a temporary variable:


```
let a = 1;
let b = 2;

[a, b] = [b, a];

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

In this example, we're swapping the values of a and b without needing a temporary variable. We do this by creating a new array with the two values in the opposite order and then using array destructuring to assign the new values to the variables.

Array destructuring is particularly useful when working with arrays that have a fixed number of elements and where you only need to extract a subset of those elements. 

<u>Extracting Data from Objects</u>

Before ES6/ES2015 extracting data from an object is done this way: 

```
let person = { name: 'Sarah', age: 29, gender: 'female' };

let name = person.name;
let age = person.age;
let gender = person.gender;

console.log(name);// ‘Sarah’
console.log(age);// ‘29’
console.log(gender);// ‘female’

```

Look at the example above and notice the repetition I explained earlier in the array example. 

With ES6/ES2015 Object Destructuring

```
const person = { name: 'Sarah', age: 29, gender: 'female' };
const { name, age } = person;
```

In the example above  the name and age properties was extracted and assigned variables with the same name. 
This will create two variables `name` and `age` with the values `'Sarah'` and `29`, respectively.

```
let { name: personName, age: personAge } = person;
```

You can also use destructuring to assign the extracted values to variables with different names. This will create two variables personName and personAge with the values 'Sarah' and 29, respectively.

One thing to keep in mind is variables in the object on the left hand side should have the same name as a property key in the object person. If the names are different, we'll get undefined. 

Values of an object can be assigned to a new variable instead of using the name of the property: 

```
let person = { name: 'Sarah', age: 29, gender: 'female' };
let {name: foo, gender: bar} = person;

console.log(foo);//’Sarah’
console.log(bar);//’female’
```

**Default Values**

Default values comes in handy in cases where a variable is undefined in an object it wants to extract data from. 

```
let person = {name: ‘Sarah’, country: ‘Nigeria’, job: ‘Developer’};

let {name = ‘myName’, friend = ‘Sophie’} = person;

console.log(name);//’Sarah’
console.log(friend);//’Annie’
```

We can also set default values when we assign values to a new variable:

```
let person = {name: ‘Sarah’, country: ‘Nigeria’, job: ‘Developer’};

let {name:foo = ‘myName’, friend: bar = ‘Sophie’} = person;

console.log(foo);// ‘Sarah’
console.log(bar);// ‘Sophie’
```

**Nested Destructuring**

You can use destructuring to extract values from nested objects and arrays. For example, consider the following object:

```
let person = { name: 'Sarah', age: 29, address: { street: '12, Admiralty St', city: 'Lagos' } };

```
To extract the street and city properties from the address object and assign them to variables with the same name, you can use the following syntax:

```
let { address: { street, city } } = person;

```

This will create two variables `street` and `city` with the values `'12 Admiralty St'` and `'Lagos'`, respectively.

You can also use destructuring to extract values from nested arrays. For example, consider the following array:

```
let numbers = [[1, 2], [3, 4]];
```

To extract the value 3 from the array and assign it to a variable, you can use the following syntax:

```
let [, [c]] = numbers;
```

This will create one variable `c` with the value `3`.

Destructuring is a powerful feature in JavaScript. It can make your code more concise and readable, and it's definitely worth learning if you haven't already. 

By using nested destructuring, you can extract values from complex data structures with ease. 

I hope this helps you! 🖤🖤🖤