tc39 / proposal-optional-chaining

https://tc39.github.io/proposal-optional-chaining/
4.94k stars 75 forks source link

Use case : var1?.field === var2?.field #139

Closed ErnestBrandi closed 4 years ago

ErnestBrandi commented 4 years ago

Hi, I'm sure this is a noob question, but why is it not documented anywhere to be very careful not to do this ? For example in this simple demo (https://jsfiddle.net/ydb9tkwp/1/)

<button id="btn">
  User Panel
</button>
// ...
const user = null; // or await fetch()
const owner = null;
if(user?.id === owner?.id) {
   document.getElementById("btn").textContent = "Admin Panel";
}

we wanna check if user's and owner's infos have been gathered (in an asynchronous situation) using optional chaining, but it might result (if not fetched) in undefined === undefined which would grant us admin access...

MatthiasKunnen commented 4 years ago

The spec explains what the operator does and how it works. If you use it in the wrong place, that is on you. Documenting all possible logic errors a developer can make is simply not feasible.

It's your responsibility to write proper code.

claudepache commented 4 years ago

@ErnestBrandi This is a logic error, not an issue with Optional chaining per se. Your example is probably appropriate in a tutorial for didactical purpose. However, the goal of this repo is not exactly didactic: it is about writing a technical proposal for inclusion in the ECMAScript standard.

ErnestBrandi commented 4 years ago

Well I'm fine with those answers :) I just felt it was redundant doing if(user && owner && user?.id === owner?.id) { ... } when the purpose of optional chaining seemed to be not to have to check parent state on nested data.

Shinigami92 commented 4 years ago

Even if(user && owner && user?.id === owner?.id) { ... } is "wrong" and dangerous!

Use:

if(
  user &&
  typeof user.id === 'number' &&
  !isNaN(user.id) &&
  user.id === owner?.id
) {
  //...
}
ErnestBrandi commented 4 years ago

Sure, or id can be a string, but I get the idea ;)