How Destructuring Works in JavaScript

Destructing helps to write less code and easy way to access the properties in JavaScript.

Object destructuring.💔

Suppose we have an object literal.

let obj={
 name:'sai',
 show:true

} 
How can we access the properties in Object?
  • The answer is we are using dot notation to access the object properties

Like we need to use obj.propertyname or obj[‘propertyname’]

let’s see the same thing using object Destructuring

Have you seen in object Destructuring we are accessing the same property in an easy way instead of writing dot notation?

Array Destructuring

Let’s see an example

How can we access elements in an array?

  • The answer is we are using its location like 0,1,2,3etc

normal

The second thing we can access using arr[‘0’]

string

Now we can access the same elements using Array Destructing instead of using its location every time.

array destruturing

How can we use Destructuring in functions?

let’s see the example

I’m passing the object as an argument to the function.

Showing without destructuring
func normal

The Same thing with Destructuring

func des

In above code, we are destructuring the object in the function parameter itself.
Have you seen how much less code we write to access the same thing?

Now we are moving to level deep

Nested destructuring💣

It is bit easy instead of we don’t need to write obj.show.items to access the items property.

Source: dev