loading...

All about Destructuring

318097 profile image Mehul Lakhanpal Originally published at Medium ・1 min read

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"],
  },
};

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.

InstagramTwitterFacebook

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

codedrops.tech

Discussion

pic
Editor guide