One really handy thing JavaScript provide us is destructuring. I love it and it can make our code much cleaner. Let us take a look at a simple piece of code:
const profile = {
name: 'Telmo',
twitter: '@telmo',
age: 34,
}
Now, if we want to access that information without destructuring it we can do the following:
profile.name // Telmo
profile.twitter // @telmo
profile.age // 34
This is totally fine, but you might notice that we keep repeating profile.?
,
at least 3 times, one for each value. We can fix this by destructuring our
profile
object:
const { name, twitter, age } = profile
name // Telmo
twitter // @telmo
age // 34
Great! Also, we can add default values while destructuring it, taking the previous example:
const { name, twitter, age, followers = 100 } = profile
name // Telmo
twitter // @telmo
age // 34
followers // 100
Alright, we now have a new value called followers
, this will always default
to 100
, unless our profile object is passing a followers
value as well,
all together:
const profile = {
name: 'Telmo',
twitter: '@telmo',
age: 34,
followers: 300,
}
const { name, twitter, age, followers = 100 } = profile
followers // 300
Since profile
is sending a value for followers
, our default value of
100
will be ignore. You can add default value to multiple items while
destructuring.
Alias
Another neat trick is creating alias while destructuring, let us look at a dummy code:
const { data } = fetchPosts()
const { data } = fetchTags()
Well, we can't do this can we? We have 2 data
constants holding data, our
code will definitely throw an error. What we can do is create alias for our
data
constants:
const { data: posts } = fetchPosts()
const { data: tags } = fetchTags()
posts // Data from `fetchPosts`
tags // Data from `fetchTags`
That's it. Hope it was useful in some way.