JavaScript Destructuring.
Tags: javascript, webdev, destructuring, programming
Published: 2023-04-04 15:40:28

##Have you ever heard of object or array destructuring? 
If you work as a developer I'm sure you have seen or used it more than once. 

In the world of JavaScript, Object and Array Destructuring are powerful tools that can simplify complex code and make it more readable. By breaking down objects and arrays into smaller, more manageable pieces, developers can write cleaner and more efficient code. 

In this article, we will explore the fundamentals of Object and Array Destructuring and how they can be used to create more concise and effective code. 🙂

Let's begin!

_First of all, we will need to declare our main object to play with it._

```js
const developer = {
  username: 'NotAbug',
  email: 'notabug@pls.com',
  networks: {
    instagram: {
      username: '@notABug-ig',
      link: 'https://instagram.com/notabug'
    },
    twitter: {
      username: '@notABug-tw',
      link: 'https://twitter.com/notabug'
    },
    youtube: {}
  }
}
```
### Simple object destructuring.
```js
const { username } = developer
console.log(username) // NotAbug
```
> Here we are using object destructuring to assign the value of the `username` property of the `developer` object to a new `username` constant.

### Nested destructuring and rename.
```js
const { networks: {
    instagram: { username: instagramUsername },
    twitter: { username: twitterUsername },
    youtube: { username: youtubeUsername = null }
}
} = developer
console.log(instagramUsername) // @notABug-ig
console.log(twitterUsername) // @notABug-tw
console.log(youtubeUsername) // null
```
> We are using nested destructuring to extract the `username` property value. Additionally, we are using renaming destructuring to rename the extracted `username` property values to `instagramUsername`, `twitterUsername`, and `youtubeUsername`.

> The `youtubeUsername` variable is also using default destructuring to set its value to `null` if it is not present in the `developer` object.

### Destructuring and rest operator.

```js
const { networks: { instagram, ...restNetworks } } = developer

const newInstagram = {
    username: '@definitelyNotABug',
    link: instagram.link
}

developer.networks = {
    ...restNetworks,
    instagram: newInstagram
}
console.log(developer.networks.instagram.username) // @definitelyNotABug
```
> Here we are using destructuring to extract the `instagram` property from the `networks` object of the `developer` object. The rest operator `...restNetworks` is used to capture all the remaining properties of the `networks` object, excluding the `instagram` property.

> Then, a new object `newInstagram` is created with the `username` and `link` properties, where the `link` property is taken from the extracted `instagram` object.

> Finally, the `developer.networks` object is re-assigned using the spread operator `...restNetworks` to include all the remaining properties of the original `networks` object, and the `instagram` property is replaced with the new `newInstagram` object.

In summary, we are essentially extracting the `instagram` property from the `networks` object of the `developer` object, creating a new object with some modifications, and then updating the `developer.networks` object to include the new object while retaining the remaining properties of the original `networks` object.

<hr/>

## Array destructuring.

Now let's see how to do it with arrays instead of objects. First, let's define a one-dimensional (`simpleArr`) and a multidimensional (`doubleArr`) array.

```js
const simpleArr = ['find', 'the', 'bug', 'pls']

const doubleArr = [
    ['find', 'the', 'bug', 'pls'],
    ['we', 'solved', 'it', '🔥']
]
```
### Simple Array Destructuring.

```js
const [firstValue, secondValue] = simpleArr
console.log(firstValue) // find
console.log(secondValue) // the
```

> We are assigning the first and second elements of the array `simpleArr` to the variables `firstValue` and `secondValue`, respectively.

**Note:** Doing this will not work to get the last element...
`const [lastValue] = simpleArr`. The assignment will occur in the order of the values in the array, so this `lastValue` will be `find`.
*You can get the last value like this e.g:* `const lastValue = simpleArr[simpleArr.length-1]`

### Jump values & assign new value.
```js
const [, , thirdValue = 'nope'] = simpleArr
console.log(thirdValue) //bug
```
> We are using destructuring assignment to extract the third value from the `simpleArr` array. The first two values are ignored and not assigned to any variables using the empty commas. If the third value is not defined in the array, the default value of `'nope'` will be assigned to the `thirdValue` variable, which is not happening since we have the value `bug` in this position.

*Example with new value:*
```js
const simpleArr = ['find', 'the', undefined, 'pls']
const [, , newValue = 'nope'] = simpleArr
console.log(newValue) // nope
```

### Get Nested arrays from a double array.
```js
const [firstArray, secondArray] = doubleArr
console.log(firstArray) // [ 'find', 'the', 'bug', 'pls' ]
console.log(secondArray) // [ 'we', 'solved', 'it', '🔥' ]
```
> As we previously did in the simple array, we are now assigning the first and second elements of the array `doubleArr` to the variables `firstArray` and `secondArray`, respectively. So now we will have one array in each variable.

### Get values from nested arrays.
```js
const [[, , third], [, second]] = doubleArr
console.log(third) // bug
console.log(second) // solved
```
> Here we are extracting specific values from `doubleArr`. The `[, , third]` syntax means that the first sub-array is being ignored (since there are two commas with no variable names in between), and the third element of the second sub-array is being assigned to a variable called `third`.

> Similarly, `[, second]` means that the first element of the second sub-array is being ignored, and the second element is being assigned to a variable called `second`.

>After this, `third` will have the value `'bug'` and `second` will have the value `'solved'`.

<hr />
And that's all folks!

I hope you discovered some new destructuring tricks with this article!

**Made with <3 by Franky Molina.**

<hr/>

*Photo by <a href="https://unsplash.com/@v_uk_europe?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Vit Ch</a> on <a href="https://unsplash.com/photos/Oxb84ENcFfU?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>*