Array Destructuring in Depth
Tags: javascript, es6, Destructuring
Published: 2020-06-04 08:32:52

In this post, our major focus will be on learning how to harness the power of destructuring to simplify our JavaScript programs.


# What does the term Destructuring mean ?

You can think of it mentally as __Decomposing a structure into individual parts__ .
The purpose of destructuring as a feature is __to assign individual parts from some larger structure.__


#### i) Let’s imagine , we’ve a function that returns us some user names.And I would grab the data and assigning it off into a variable , say awesomeTeachers.

```js
function instructors(){
return ['Will','Kyle','Jonas'];
}
var awesomeTeachers= instructors();
```
Now  , I want to get these three usernames into three different variables.
Let's follow the normal approach first :

Normally , I would be assigning off the individual element values into three different variables like this :

```js
function instructors(){
return ['Will','Kyle','Jonas'];
}
var awesomeTeachers= instructors();

var teacherOne = awesomeTeachers[0];
var teacherTwo = awesomeTeachers[1];
var teacherThree = awesomeTeachers[2];

console.log(teacherOne );       // Will
console.log(teacherTwo );       // Kyle
console.log(teacherThree );     // Jonas
```

Now , let's use Destructuring approach:

```js
function instructors(){
return ['Will','Kyle','Jonas'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = instructors();
```
That's it. We have reduces plenty of lines of code by this approach.

Now , let's handle the varieties of this example:

### a) What will happen if we removed the third name from the array i,e 
```js
function instructors(){
return ['Will','Kyle'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = instructors();
```
Now , teacherThree will be __undefined__.
__Remember__ , if our destructuring pattern indicates something that doesn’t exist, then it just gets assigned __undefined__ .

### b) I had an extra value but we didn’t account for it on the left-hand side i,e

```js
function instructors(){
return ['Will','Kyle','Jonas','Andrew'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = instructors();
```
Nothing significant will happen ,last value i,e 'Andrew' just get ignored.

### c) What if it was possible for one of these positions to come back as __undefined__ ?

```js
function instructors(){
return ['Will',,'Jonas',];
}

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = instructors();
```
In this case, value of teacherTwo would be __undefined__ .
It would always be best to provide some sort of default.

```js
function instructors(){
return ['Will',,'Jonas',];
}

let [ teacherOne,
      teacherTwo = 'teacher',
      teacherThree
    ] = instructors();
```
__Note:__ 
* It’s important to understand that the default value expression only applied when there’s an __undefined__ .
* If I got __null__ instead of __undefined__ what the variable teacherTwo would be __null__ not the default value provided.

### d) What if our array had several other names in it and I couldn’t predict how many values it had in it? But I want all of them to have to be collected up into an array ?

We can use the __gather__ or __rest__ syntax. 

```js
function instructors(){
return ['Will','Kyle','Jonas','Wes','Andrew','Dylan','Maximilian'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree,
      ...fourth
    ] = instructors();
```

### e) Till now , we've been directly gathering the values in appropriate variables. But it might be the case that we’d actually like to have a reference to the whole structure as well.
Then we need to do this :

```js
function instructors(){
return ['Will','Kyle','Jonas'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree,
    ] = wholeArray = instructors();
```
Here , first __wholeArray__ will get assigned the array and then that array is gonna get destructured by the given pattern.


#### ii) Declaration-assignment


We can also declare the variables first and then use destructuring pattern.Let's have a look:

```js
function instructors(){
return ['Will','Kyle','Jonas'];
}

let wholeArray = instructors();

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = wholeArray ;
```
### a) Assigning to objects:

If we’re can assign them to variables that already exist, we could also assign them to entirely other locations.Let's see :

```js
function instructors(){
return ['Will','Kyle','Jonas'];
}

wholeArray = instructors();
let obj = { };

let [ obj.teacherOne,
      obj.teacherTwo,
      obj.teacherThree
    ] = wholeArray ;
```

### b) Assigning to array:

In the same way as we did for objects, we can also assign them to any array position :

```js
function instructors(){
return ['Will','Kyle','Jonas'];
}

wholeArray = instructors();
let arr= [ ];

let [ arr[0],
      arr[1],
      arr.[2]
    ] = wholeArray ;
```


#### iii) Comma Seperation


What if I didn't care about any name in the array ?
We can ignore them just by using __comma__ . Let's see:
If I don't want our second item i,e 'Kyle' , we can just use comma at that place.
```js
function instructors(){
return ['Will','Kyle','Jonas'];
}

wholeArray = instructors();

let [ teacherOne,
      ,
      teacherThree,
    ] = wholeArray ;
```


#### iv) Parameter Arrays


If we can do array destructurings on our assignment list, __we can also do them in parameter positioning .

```js
function data([
  teacherOne,
  teacherTwo,
  teacherThree
]) {
    // ...
}
```


#### v) Providing Defaults:


```js
function instructors(){
return null;
}

wholeArray = instructors();
let arr= [ ];

let [ teacherOne,
      teacherTwo,
      teacherThree,
    ] = wholeArray ;
```

In the above code , what would happen if our function __instructors__ didn't returned any array or returned __null__ ?
We’ll get a __type error__ .

So , in order to fix this  , we can provide a __default empty array__ , so that if data comes back __false__ from function , then it will just pick up the __empty array__ .

```js
function instructors(){
return null;
}
instructors();

let arr= [ ];

let [ teacherOne,
      teacherTwo,
      teacherThree,
    ] = instructors() || [ ];
```
The only motive of this was to save ourself from __typeError__.
teacherOne , teacherTwo and teacherThree are still __undefined__ .

* We can do the same thing in parameter too :

```js
function data([
  teacherOne,
  teacherTwo,
  teacherThree
] = []) {
    // ...
}
```


#### vi) Nested Array Destructuring


Let's use destructuring for Nested Array.
In destructuring , if we have a position inside an array that is also an array, then we need to break that thing down again as a destructuring pattern.
Let's see-

```js
function instructors(){
return ['Will',['Kyle','Kent'],'Jonas'];;
}
instructors();

let arr= [ ];

let [ teacherOne,
     [
      teacherTwo,
      teacherThree
     ],
      teacherFour
    ] = instructors() || [ ];
```

So at position two, instead of having the target be a variable, we want the target to be another destructuring pattern.

### a) What if instead of getting subarray at position two , we got undefined ?
Again ,we’re gonna get __type error__ .
So , just like we did earlier , we can provide empty array as default here too :

```js
function instructors(){
return ['Will',['Kyle','Kent'],'Jonas'];;
}
instructors();

let arr= [ ];

let [ teacherOne,
     [
      teacherTwo,
      teacherThree
     ] = [ ],
      teacherFour
    ] = instructors() || [ ];
```

#### vii) Swaping Two variables
We can use destructuring assignment to swap the values of variables.

```js
let firstName = 'Will';
let lastName = 'Sentance';

[ firstName , lastName ] = [ lastName , firstName ]
```

#### Conclusion

JavaScript is full of complex objects and arrays. Whether it’s the response from an HTTP request, or static data sets, being able to access the embedded content efficiently is important. Using destructuring assignment is a great way to do that. It not only handles multiple levels of nesting, but it allows for focused access and provides defaults in the case of undefined references.


Thank you or reading :)

If you have any question regarding this or anything I should add, correct or remove, feel free to comment, email or DM me. Thanks !!!