What is destructuring in JavaScript?
Tags: javascript, webdev, beginners, tutorial
Published: 2023-01-07 21:08:42

Destructuring in JavaScript means copying the values of an array or the properties of an object to a variable.
Destructuring does not imply destruction. It is not the case because the array or object you could copy the values from is not modified.
This is a JavaScript expression that was introduced in ECMAScript 2015/16.
In this article, you will learn how to destructure values in an array, properties in an object, and other uses of destructuring.

![destructuring in javascript text written](https://i.imgur.com/1jXr46w.png)


## Basic destructuring in arrays

Destructuring makes it easier to access the values of an array.
For example,
If you want to access values in an array without destructuring,

```javascript
const array = ["deer","greet","heyy"];

const arr = array[0];
const arr1 = array[1];

console.log(arr);                //deer
console.log(arr1);              //greet
```

In this example, you assigned the values by using their index. But with destructuring, this is how it will be.

```javascript
const array = ["deer","greet","heyy"];

const [arr,arr1,arr2] = array;

console.log(arr);                  //deer
console.log(arr1);               //greet

```

So you could assign the values of the `array` variable to the new variables all at the same time.

**Swapping values**
In arrays, you could swap the values in a variable by switching places. Usually, you would need a third variable to achieve this.


Here's an example:

```javascript
let arr = "deer";
let arr1 = "greet";

console.log(arr);                //deer
console.log(arr1);             //greet

let newArr = arr1;         //assigning the value "greet" to a new variable "newArr"

console.log(newArr);          //greet

arr1 = arr;           //assigning the value "deer" to the variable "arr1"

arr = newArr;        //assigning the value "greet" to the variable "arr"

console.log(arr1);           //deer
console.log(arr);            //greet
```
But with destructuring, you can do that without a third variable.

```javascript
const array = ["deer","greet","heyy"];

let [arr,arr1,arr2] = array;

console.log(arr);                //deer
console.log(arr1);             //greet

[arr,arr1] = [arr1,arr];        //using destructuring to swap the values 

console.log(arr);               //greet
console.log(arr1);             //deer 

```
**Skipping Values**

You could also skip values when assigning values to a variable. You do that by adding an extra comma to the array you are destructuring the values to. The comma indicates the index of the value.


In this example, a comma at the assignment's beginning indicates the array's first value.

```javascript
const array = ["deer","greet","heyy"];

const [,arr1,arr2] = array;             //skipping the first value and using only the second and third

console.log(arr1);              //greet
console.log(arr2);              //heyy
```


## Using array-destructuring with iterators
Array destructuring works on all iterable values. You can array-destructure any iterable value. Examples of such iterables are strings, sets, and so on.

For example, using array destructuring on a string,

```javascript
const [a,b] = "abc";

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

example of using array destructuring on a set,

```javascript
const array = ["deer","greet","heyy"];

const exampleSet = new Set(array);

const [arr,arr1,arr2] = exampleSet;

console.log(arr);         //deer
console.log(arr1);        //greet
console.log(arr2);        //heyyy

```

Array-destructuring works on iterable values only. Non-iterable values would give an error. Examples of non-iterables are null and undefined.

Also, javascript would return undefined if the array you are destructuring is empty.

for example,

```javascript
const [arr,arr1] = [];

console.log(arr);          //undefined

console.log(arr1);         //undefined
```

Here is another scenario:

```javascript
const array = [];

const [arr,arr1] = array;

console.log(arr);          //undefined

console.log(arr1);         //undefined

```

## Default values in arrays
When writing code, there are cases where you may be unsure of the values you are assigning. If that value is `undefined`, you would need a default value. Destructuring makes it easier for you to assign default values to an array.

See this example:

```javascript
const array = ["deer","greet","heyy"];

const [arr,arr1,arr2,arr3] = array;

console.log(arr);              //word
console.log(arr1);            //fang
console.log(arr2);           //grey
console.log(arr3);           //undefined

```

To assign a default value to `arr3`

```javascript
const array = ["deer","greet","heyy"];

//To assign a default value to arr3
const [arr,arr1,arr2,arr3="mirrors"] = array;

console.log(arr3);          //mirrors
```

With that, you can assign a default value to a variable while destructuring.


## Using the rest syntax
Destructuring in Javascript also uses the rest syntax. It is called the "rest" syntax as it covers the rest of the items in an array. The syntax is `...` then the name of the array created. The name "rest" that appears after the three dots is optional. You could use another name after the three dots.

Syntax:
`(...rest)`

When using the rest syntax, always make sure it comes last after other items, as it will give an error if you do otherwise.

Here's an example of rest in an array:

Using the previous example,


```javascript
const array = ["deer","greet","heyy"];

const [arr, …newArr] = array;

console.log(arr);               //deer
console.log(newArr);          //[ greet, heyy]
```
As you can see, the `newArr` array was created from the old array.



## Object destructuring
With object destructuring, you can retrieve property values from an object. Objects take a different syntax from arrays when assigning values to variables.

To assign values without destructuring would be:

```javascript
const obj = { word: "dataTypes", num: 0001, bool: true, bigInt: 2.99999999};             //example of the object

//To access the object property

const words = obj.word;              

const boolean = obj.bool;                     

console.log(words)             //dataTypes
console.log(boolean)          //true

```

This is how to assign values to objects using destructuring.

```javascript
const obj = { word: "dataTypes", num: 0001, bool: true, bigInt: 2.99999999};            //example of the object

//To access the object property
const { word, bool } = obj;                   

console.log(word)       //dataTypes
console.log(bool)      //true 

```

This makes value assignments easier.

_**Note:** The order does not matter in objects, and you should use the same name._

This would result in the following error:

```javascript
const obj = { word: "dataTypes", num: 0001, bool: true, bigInt: 2.99999999};

const { words, boolean } = obj;

console.log(words)           
console.log(boolean)       

//ReferenceError: obj is not defined
```

This is because JavaScript does not store the `words` and `boolean` variables as references for the object, hence the error.

However, you can assign different names to the values while destructuring.

**Assigning different names to the object properties**

You can assign different names to the object properties to access them.

```javascript
const obj = { word: "dataTypes", num: 0001, bool: true, bigInt: 2.99999999};

const { word: words, bool: boolean } = obj;

console.log(words)               //dataTypes
console.log(boolean)           //true

```

**Using object destructuring on arrays**
You can use the index of an array as a "property" when you apply object destructuring to arrays.

```javascript
const {0:arr, 1:arr1, 2:arr2} = ["deer","greet","heyy"];

console.log(arr);          //deer
console.log(arr2);         //heyy


```

**Initial declaration of variable**

In objects, you could declare a variable initially before you assign a value to it.

```javascript
let word;

const obj = { word: "dataTypes", num: 0001, bool: true, bigInt: 2.99999999 };

({ word } = obj);

console.log(word);   //dataTypes    

```

_**Note:** during an assignment, use parentheses, or JavaScript would see it as a block function and return a syntax error._


## Using the rest syntax in objects

You could use the rest syntax in an object. Like in arrays, the rest syntax comes at the end and covers the remaining properties in an object. 

Here's an example:

```javascript
const obj = { word: "dataTypes", num: 0001, bool: true, bigInt: 2.99999999};            //example of the object

//To access the object property
const { word: words, ...others } = obj;                   

console.log(words);              //dataTypes
console.log(others);            //{ num:0001, bool:true, bigInt:2.99999999 } 

```
**Note:**
*Like in arrays, javascript would return `undefined` when it is set to destructure an empty object. Object destructuring will return a type error when the values are `undefined` and `null`.*

## Default values in objects

In an object, you could assign default values to variables when destructuring. If a property was not in the object, you could create a variable and assign a default value to it.

For example,

```javascript
const obj = { word: "dataTypes", num: 0001, bool: true, bigInt: 2.99999999, };            //example of the object

//To access the object property
const { word, bool, num, str="street" } = obj;                   

console.log(word);             //dataTypes
console.log(str);              //street
```

In this example, the default value `street` was assigned to the `str` variable while destructuring.

## Summary 

That sums up the main features of destructuring in JavaScript. I hope you learned something from this. If you liked this piece, you could share it with a friend or leave a comment. Thanks for reading.
Need more information? Check out this guide for more on [destructuring in javascript](https://2ality.com/2015/01/es6-destructuring.html).