DEV Community

Discussion on: Optional Chaining may be coming to JavaScript

Collapse
 
blunket profile image
Andrew Siegman

This seems like a useless way to silence errors to me. (specimen?.arms?.length > 2) will return false if specimen is undefined, if arms is undefined, if arms happens to be a boolean for some reason, or if specimen.arms.length is 1.. wouldn't you need to treat these things all differently? So what's the point of this?

Collapse
 
sammyisa profile image
Sammy Israwi

It all depends on the situation. Sure, sometimes you need to check if you have specimen or arms because you would have to handle those scenarios differently. Say, notifying the user that they need to have a specimen in the first place, or populate it yourself.

But if you have specimen and all you need to do is to check if it is an alien or not, this syntax fits like a glove. I don't need to check and handle every single property before the one that I actually need, that's why in JavaScript we have a bunch of if conditions that look like this:

if(user && user.details && user.details.dateOfBirth && user.details.dateOfBirth.month === Month.March)
  console.log("You were born in March");

And as far as arms being a Boolean, this proposal is not trying to fix type issues with the language. For that kind of problems, it would be better to look at TypeScript, or Flow.

Collapse
 
blunket profile image
Andrew Siegman

I suppose you're right, it is inconvenient to have to do that. But I feel like this problem can be solved with a better design in the object structure. For this specific example, why would the object not just have a static boolean property like specimen.alien or something? Following a better design guideline like the Law of Demeter would solve this, right? It seems like this proposal may encourage (or at least fail to discourage) messy object structures. I only brought up the boolean example cause this is solving a common TypeError, but I see your point.

(p.s.: i am debating with good intentions, mainly cause i see no counterarguments aside from my own, not trying to start a flamewar)

Thread Thread
 
sammyisa profile image
Sammy Israwi • Edited

Well, I do agree that the problem can be solved with better object design from the developer's side. A snippet like this one:

if(user.isBornInMarch)
  console.log("You were born in March!");

is fairly readable.

However, it depends heavily on a developer having the foresight to design a class like so and the other developers knowing of this design detail.

The other thing to remember is that this proposal is not intended to give JS a new language feature or give developers the ability to do something that they haven't been able to do before, it is just to make the life of the developer a little bit easier and the resulting code a little bit easier to read.

I understand debating with good intentions, I appreciate that. No one here wants to start an actual flamewar :)