Object destructuring in Javascript | Real time example | Good Practice
Ashish Singh Rawat
Posted on September 21, 2021
I was working on my project and got a review comment from my colleague to put the default value for the nested object, as it could break the app.
Below was the response object structure that I was getting from an API call.
response = {
data:
someData: {
name: 'Ashish',
number: 9876543210
}
}
}
only name
and number
were getting used in the code. The code I had written previously for which I have received the comment looked as below.
const { name, number } = response.data.someData;
PROBLEM
Now the problem with above code is,
- if Backend doesn't share the data object. Then JS the engine will try to find someData in
undefined
. This could have broke the application - I wanted to write everything in one line, instead of destructuring multiple times
So to avoid the above problem, I had to google and search for a good practice for javascript multilevel destructuring with default values. And here is what I got
SOLUTION
const { data: { someData: { name, number } } = { someData: { name: '', number: null } } } = response;
- code doesn't break, as we are setting default values for the response object in the frontend.
- Clean code
- Readable (This point is argued, depends on developer perspective)
EXPLANATION
If you haven't tried multilevel destructuring, above code might look little confusing, let's break the above code into multiple statements
1. Destructuring Multilevel
const {
data:
{ someData:
{
name,
number
}
}
} = response;
//OR
// In one line
const { data: { someData: { name, number } } } = response;
This is how we destructure a multilevel object. With parent object data
outside pointing to the child object someData
and then the child object someData
referring to the child object having values name
and number
.
2. Assigning default value
if data
doesn't exist in the response object, assign a default value to it
const { data = {} } = response;
If data
doesn't exist in response, then data with empty object is created inside the response
Note:
Default values go to the right hand side and =
is used to assign the value.
const {
data: {
someData: {
name,
number
}
} = { someData: { name: '', number: null } } } = response;
// OR
// in 1 line
const { data: { someData: { name, number } } = { someData: { name: '', number: null } } } = response;
This creates an object with someData
with name
default value is ''
empty string and number
's default value as null
.
Note:
''
empty string and null
are falsy values.
Posted on September 21, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 21, 2021