DEV Community

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

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.