DEV Community

Discussion on: Destructuring JavaScript objects like a pro

Collapse
 
merri profile image
Vesa Piittinen • Edited

I'd advice against deeply nested destructures like the given example:

const {
  classs: {
    infra: {
      name: homoSapiensInfraClass = ''
    } = {}
  } = {}
} = homoSapiens;

There is classs there, which could be a typo and it would easily go totally unnoticed.

Another point I'd like to make is that it is very hard to read the above. Just do:

const homoSapiensInfraClass = homoSapiens['class'].infra.name || ''

Or if you want to allow all objects to miss:

import get from 'lodash/get'

const homoSapiensInfraClass = get(homoSapiens, 'class.infra.name', '')

Much easier to understand what is happening. If you want to get multiple items you could use array destructuring:

const [homoSapiensInfraClass, homoSapiensFamily] = [
    'class.infra.name',
    'family'
].map(item => get(homoSapiens, item, ''))

Although this makes sense only if you have a whole lot of those. This example is good because it retains the normal reading order, while renaming while destructuring fights against the normal reading order. Rename in destructuring should be used sparingly to keep code easy to read.

Collapse
 
willamesoares profile image
Will Soares

Hey Vesa, thank you for the suggestion. I appreciate your contribution.

As for your concern on legibility I would take that more as a preference matter, I personally don't see that as a very hard thing to read but I understand your point.

I think the option you gave it's nice if you want things to explicitly fail so you'd be aware of possible typos. In a context in which you don't know what to expect for the structure of the homoSapiens object for instance I'd prefer to be safe and set default values for each object being destructured, instead of receiving errors like Cannot read property 'x' of undefined.

And yeah, if you can use lodash then go for it ;)

Collapse
 
timkor profile image
Timkor

I think it's by purpose. class is a reserved keyword. Although possible to use in some modern browser, I bet IE doesn't like this.

Collapse
 
brittanmcg profile image
Brittan McGinnis

I would agree with you. I think that just because you can doesn't necessarily mean that you should. I do appreciate the knowledge sharing though and it is interesting to see the different ways that it's possible to destructure.