Destructuring was introduced in ES2015/ES6. The following things can be done on an object/array:
- Extract values
- Provide a default value
- Extract value and rename the variable
Let's go with the following data and see 6 examples. All the examples are based on this data.
const response = {
msg: "success",
tags: ["programming", "javascript", "computer"],
body: {
count: 5,
data: ["File 1", "File 2"],
},
};
The basic syntax is:
const {
destructuredKey: newNameForDestructuredKey = "defaultValue"
} = obj;
1 - Destructuring the key msg
const { msg } = response;
2 - Destructure the 2nd element (i.e., javascript
) from response.tags
const {
tags: [, secondElement],
} = response;
3 - Destructuring the key msg
and renaming it to message
const { msg: message } = response;
4 - Destructuring a key which does not exist with a default value
const { searchString = "programming" } = response;
5 - Destructuring the nested key count
from response.body
const {
body: { count },
} = response;
Here, first body gets destructured, then count is again destructured from body.
Pitfall 1 - What if the body
key did not exist in the data? It would throw an error while destructuring count
because body
is undefined
.
Solution: - Provide a default value to body ({}
)
const { body: { count } = {} } = response;
Pitfall 2 - What if response was undefined?
const { msg } = undefined; // error
Super simple,
const { msg } = response || {};
If response is falsy (undefined or null), then it takes it as an empty object.
6 - Destructure File 1
from response.body.data
const {
body: {
data: [file1],
},
} = response;
Thanks for reading 💙
Follow @codedrops.tech for daily posts.
Instagram ● Twitter ● Facebook
Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript
codedrops.tech
Top comments (0)