Optional Chaining Gotchas?

Since Optional Chaining is in “Stage 3” and ready for adoption, have you had the chance to refactor any code to use Optional Chaining? Any surprises I should be wary of?

We use this quite a lot in Ruby, and the biggest gotcha is remembering the syntax so far. It’s really a nice pattern. One thing that I could think of would be a default value. When I use get in lodash, I can set a default which I like over undefined. Not strictly a gotcha, but something that optional chaining doesn’t provide explicitly.

Not necessarily a ‘gotcha’, but I always feel like this is strange that a delete operation always returns true even if the property doesn’t exist.

example:

const obj = {
  a: {
    b: 0,
  },
};

let test = delete obj?.a?.b; //true
test = delete obj?.a.b; //true
test = delete obj?.b?.b; //true
delete obj?.a; //true

I know that its the behavior of the delete keyword that’s doing this, but it feel especially strange with optional chaining. I think I’d prefer a returned false if something can’t be deleted

2 Likes