r/javascript • • Feb 20 '18

Optional Chaining may be coming to JavaScript

https://dev.to/sammyisa/optional-chaining-may-be-coming-to-javascript--4ff0
321 Upvotes

100 comments sorted by

View all comments

3

u/propelol Feb 20 '18

I prefer using destructuring and defaulting, which works today:

const {
  arms: arms = []
} = specimen

arms.length > 2

1

u/NoInkling Feb 21 '18

It's not the easiest thing to read however. Especially if you try and go more than one level deep.

1

u/propelol Feb 22 '18 edited Feb 22 '18

It surprisingly easy to go multiple levels deep. It looks weird at first, but you'll get used to it:

const {
  limbs: {
    arms: arms = 0
  } = {},
  head: {
    eyes: {
      leftEye: leftEye = true,
      rightEye: rightEye = false
    } = {},
  } = {}
} = specimen

Note: this does more than the optional chaining does, since it also defaults the missing values, and pull them out of the object

1

u/NoInkling Feb 22 '18

Firstly, you know that if you want your variables to be named the same as your properties, you can simplify that a bit right?

const {
  limbs: {
    arms = 0
  } = {},
  head: {
    eyes: {
      leftEye = true,
      rightEye = false
    } = {}
  } = {}
} = specimen

Secondly, I know you can do it (and can get used to reading it, like most things), but that doesn't help other people who are attempting to make sense of it. It doesn't just look "weird", it looks like a horrible mess. I'd much rather have the far more intuitive (imo) proposal.

In saying that, I'm not opposed to using (and have used) destructuring defaults in basic cases, e.g. in your original:

const { arms = [] } = specimen

But there's no way I'd use the nested form.