DEV Community

Discussion on: Modern JavaScript, 10 things you should be using, starting today

Collapse
 
morganconrad profile image
Morgan Conrad • Edited

The destructuring argument is unconvincing: the "old fashioned" code is extremely clear, easier to update if the structure of the object changes, and allows one to change the variable name, if needed, for even more clarity, e.g.

const nameNeedsValidation = req.param.name.

As others have noted, the Object Spread comment about needing looping is wrong: Object.assign() does the job nicely. IMO, it is also clearer than using spread, but I admit that's just my opinion.

Collapse
 
patrickb profile image
Patrick Bradshaw

Destructuring like so:

const { name: nameNeedsValidation } = req.param

Creates a variable called nameNeedsValidation from the property req.param.name.

I find it preferable to destructure in the case of when I'm working on a React class component and the state object is complex (10+ properties).

In the template, instead of having to write:

<>
   <h3>Hi I'm {this.state.name}</h3>
   <span>Name: {this.state.name}</span>
   <span>Address: {this.state.address}</span>
   <span>Zip Code: {this.state.zipCode}</span>
</>
Enter fullscreen mode Exit fullscreen mode

I can just write:

const { name, address, zipCode } = this.state
//...
<>
   <h3>Hi I'm {name}</h3>
   <span>Name: {name}</span>
   <span>Address: {address}</span>
   <span>Zip Code: {zipCode}</span>
</>
Enter fullscreen mode Exit fullscreen mode

Note that this would be unconventional:

const name = this.state.name
const address = this.state.address
const zipCode = this.state.zipCode
// ... 
Enter fullscreen mode Exit fullscreen mode

React class components are "old school" now I think, but destructuring is convenient any time you have to work with a complex object in which the properties have to referenced multiple times. That's the use case I'm most familiar with.