DEV Community

Cover image for How Destructuring Works in JavaScript💢💢💢
Sai gowtham
Sai gowtham

Posted on

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

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

Hope you guys enjoyed!!!!! If you have any doubts feel free to ask.
Happy coding........

Top comments (2)

Collapse
 
perrydbucs profile image
Perry Donham

One of the overlooked but incredibly useful ways to use destructuring is in the interface of a function. Think of a function with a signature such as:

const aFunc = function (size, weight, length, girth, width) { }

When writing client code that invokes this function, the developer has to either remember the correct order of the parameters or spend time looking it up.

With destructuring, we can write the function to take a single object as the input param:

const aFunc = function ( {size, weight, length, girth, width} ) { }

Now the dev simply writes the function call and passes an object with the appropriately named attributes:

const params = {
   size: 20,
   width: 30,
   length: 10,
   weight: 5,
   girth: 100
}

let result = aFunc(params)

The order of the named parameters now doesn't matter, since as long as the names are the same the function's parameters will be automatically populated. Combine this with default values for the input parameters and you significantly reduce the effort required to use the function.

Collapse
 
droidmakk profile image
Afroze Kabeer Khan. M • Edited

I think this one is also good!

[obj.param]=object.val