DEV Community

Discussion on: 😰 Optional chaining trap !

Collapse
smeijer profile image
Stephan Meijer

idx works indeed similar, but it does provide a little bit less over overhead.

optional-chaining, 443 bytes vs idx, 254 bytes. As the original is only 83 bytes, they both come with an overhead.

I should be happy that optional chaining has reached stage 3. As we are using the proposal for quite some time now. But instead, I'm worried. I see it being heavily overused in some places, because it's so easy to use.

function CommentButtons({ user }) {
  return (
    <div>
      <Button disabled={user?.can?.reply}>reply</Button>
      <Button disabled={user?.can?.delete}>delete</Button>
    </div>
  )
}

Easy right? Both buttons are disabled if lacking the proper permissions. This however compiles down to 731 bytes and a lot of ternary operators, while we could simply reduce this down to something like:

function CommentButtons({ user, can = user ? user.can : {} }) {
  return (
    <div>
      <Button disabled={can.reply}>reply</Button>
      <Button disabled={can.delete}>delete</Button>
    </div>
  )
}

If it's your own code base. It's safe to make some assumptions. For example, to say that if the user is set, that it's guaranteed to have a can property wich is an object.

Collapse
devinrhode2 profile image
Devin Rhode

When browsers finally start shiping support for optional chaining.... the amount of bytes sent over the wire can decrease quite a bit.... but that's going to take some time right?

Collapse
wintercounter profile image
Victor Vincent • Edited on

{ user: { can = {} } }

Thread Thread
smeijer profile image
Stephan Meijer

I'm aware of that syntax. But defaults don't work for null values. As grapql tends to return null for missing data, I don't use that syntax that much.

In a real world scenario, I would have moved the assignment out of the arguments.

Thread Thread
wintercounter profile image
Victor Vincent

Makes sense!