DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at Medium

All about Destructuring

Destructuring was introduced in ES2015/ES6. The following things can be done on an object/array:

  1. Extract values
  2. Provide a default value
  3. 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"],
  },
};
Enter fullscreen mode Exit fullscreen mode

The basic syntax is:

const { 
  destructuredKey: newNameForDestructuredKey = "defaultValue"
} = obj;
Enter fullscreen mode Exit fullscreen mode

1 - Destructuring the key msg

const { msg } = response;
Enter fullscreen mode Exit fullscreen mode

2 - Destructure the 2nd element (i.e., javascript) from response.tags

const {
  tags: [, secondElement],
} = response;
Enter fullscreen mode Exit fullscreen mode

3 - Destructuring the key msg and renaming it to message

const { msg: message } = response;
Enter fullscreen mode Exit fullscreen mode

4 - Destructuring a key which does not exist with a default value

const { searchString = "programming" } = response;
Enter fullscreen mode Exit fullscreen mode

5 - Destructuring the nested key count from response.body

const {
  body: { count },
} = response;
Enter fullscreen mode Exit fullscreen mode

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

Pitfall 2 - What if response was undefined?

const { msg } = undefined; // error
Enter fullscreen mode Exit fullscreen mode

Super simple,

const { msg } = response || {};
Enter fullscreen mode Exit fullscreen mode

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

Thanks for reading 💙

Follow @codedrops.tech for daily posts.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Top comments (0)