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: {}
}
}
Simple object destructuring.
const { username } = developer
console.log(username) // NotAbug
Here we are using object destructuring to assign the value of the
username
property of thedeveloper
object to a newusername
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
We are using nested destructuring to extract the
username
property value. Additionally, we are using renaming destructuring to rename the extractedusername
property values toinstagramUsername
,twitterUsername
, andyoutubeUsername
.The
youtubeUsername
variable is also using default destructuring to set its value tonull
if it is not present in thedeveloper
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
Here we are using destructuring to extract the
networks
object of thedeveloper
object. The rest operator...restNetworks
is used to capture all the remaining properties of thenetworks
object, excluding theThen, a new object
newInstagram
is created with theusername
andlink
properties, where thelink
property is taken from the extractedFinally, the
developer.networks
object is re-assigned using the spread operator...restNetworks
to include all the remaining properties of the originalnetworks
object, and thenewInstagram
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', '🔥']
]
Simple Array Destructuring.
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 variablesfirstValue
andsecondValue
, 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
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 thethirdValue
variable, which is not happening since we have the valuebug
in this position.
Example with new value:
const simpleArr = ['find', 'the', undefined, 'pls']
const [, , newValue = 'nope'] = simpleArr
console.log(newValue) // nope
Get Nested arrays from a double array.
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 variablesfirstArray
andsecondArray
, 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
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 calledthird
.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 calledsecond
.After this,
third
will have the value'bug'
andsecond
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.
Top comments (8)
Variable names used in destructuring can also be dynamic:
Thank you for showing that use! 🔥
Be careful with nested destructuring though, your code will become harder to interpret for a human. But otherwise, good article 👍
Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍
JavaScript destructuring is a useful technique to have in your toolkit, and it can help you write cleaner, more expressive code.
Great and helpful article! 🔥🔥
Nice article, mate!! 👏🏻
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?