JavaScript - Destructuring



Destructuring is a simple term we can use to extract values from array and properties from object. It is a JavaScript expression that help to unpack values from array or similarly properties from object into different variables.

Let's say you have a box that contain multiple items. Now, imagine someone asks you to take out a particular item from the box, then you will need to check each item one by one and this increases complexity right? Then we just simplify it by using destructuring and get the exact item at once.

When to use Destructuring?

We use destructuring in the following scenarios −

  • When we need more than one property from object or more than one value from the array, we can use destructuring for that.
  • Suppose, there is a situation where we need to assign more than one value to variables, we can use destructuring to achieve it.
  • If we need to pass an object as a function parameter, we can use destructuring to extract the properties of the object.
  • If there is a need to return multiple values from a function, we can use destructuring to return them as an object.
  • It is easy to use destructuring when working with arrays and objects.

Types of Destructuring

There are two types of destructuring in JavaScript those are shown below −

  • Object Destructuring: It is used to extract properties from an object.
  • Array Destructuring: It is used to extract elements from an array.

Object Destructuring

Object destructuring means when we extract some properties from an object and assign them to variables. It allow us to write short code and also it helps us to improve our code readability.

Array Destructuring

Array destructuring is Same as object destructuring, We can also destructure an array, extract elements from an array and assign them to variables.

Advertisements