DEV Community

Cover image for JavaScript Destructuring.
FrankyMolina
FrankyMolina

Posted on

JavaScript Destructuring.

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.

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: {}
  }
}
Enter fullscreen mode Exit fullscreen mode

Simple object destructuring.

const { username } = developer
console.log(username) // NotAbug
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode

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.

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

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

developer.networks = {
    ...restNetworks,
    instagram: newInstagram
}
console.log(developer.networks.instagram.username) // @definitelyNotABug
Enter fullscreen mode Exit fullscreen mode

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.


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.

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

const doubleArr = [
    ['find', 'the', 'bug', 'pls'],
    ['we', 'solved', 'it', '🔥']
]
Enter fullscreen mode Exit fullscreen mode

Simple Array Destructuring.

const [firstValue, secondValue] = simpleArr
console.log(firstValue) // find
console.log(secondValue) // the
Enter fullscreen mode Exit fullscreen mode

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.

const [, , thirdValue = 'nope'] = simpleArr
console.log(thirdValue) //bug
Enter fullscreen mode Exit fullscreen mode

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:

const simpleArr = ['find', 'the', undefined, 'pls']
const [, , newValue = 'nope'] = simpleArr
console.log(newValue) // nope
Enter fullscreen mode Exit fullscreen mode

Get Nested arrays from a double array.

const [firstArray, secondArray] = doubleArr
console.log(firstArray) // [ 'find', 'the', 'bug', 'pls' ]
console.log(secondArray) // [ 'we', 'solved', 'it', '🔥' ]
Enter fullscreen mode Exit fullscreen mode

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.

const [[, , third], [, second]] = doubleArr
console.log(third) // bug
console.log(second) // solved
Enter fullscreen mode Exit fullscreen mode

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'.



And that's all folks!

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

Made with <3 by Franky Molina.


Photo by Vit Ch on Unsplash

Top comments (8)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Variable names used in destructuring can also be dynamic:

const {length, [length-1]: last} = "Hello!"
console.log(length)  // 6
console.log(last)  // '!'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
frankymolina profile image
FrankyMolina

Thank you for showing that use! 🔥

Collapse
 
brense profile image
Rense Bakker

Be careful with nested destructuring though, your code will become harder to interpret for a human. But otherwise, good article 👍

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
wizdomtek profile image
Christopher Glikpo ⭐

JavaScript destructuring is a useful technique to have in your toolkit, and it can help you write cleaner, more expressive code.

Collapse
 
xexuline profile image
Jesus Sabroso

Great and helpful article! 🔥🔥

Collapse
 
robertoheci profile image
Roberto Hernández

Nice article, mate!! 👏🏻

Collapse
 
akbarnafisa profile image
Akbar Nafisa

I love destructuring in Javascript, but from my experience, I always get NPE that breaks the page 😅. Do you have any tips for avoiding this?