1

I found a really great use case for optional chaining in my react project. I have used it slightly before but this line of code has made me a bit confused.

I have a table that is sortable. One of the columns shows success or failure depending on if failed_date is null or a date.

sortedRows = sortedRows.sort((a, b) => a?.failed_date?.localeCompare(b?.failed_date));

But What confuses me is which value does the '?.' check is nullish?

Does a.failed_date?.localeCompare() check if failed_date?. is null/undefined or does it check if ?.localeCompare() is null/undefined?

Same with b?.failed_date is it checking b to be nullish? or failed_date.

I think My confusion comes from looking at the Documentation

Because arr?.[50] checks if element 50 is nullish but obj.method?.() checks if the method is not nullish?

Looking at this second block of code (which I believe is now correct) a.failed_date may be nullish and won't do localeCompare if a.failed_date is null? But what if a.failed_date is not null but b.failed_date is null? Does localeCompare not care? I haven't gotten an error but I was using localeComapre(b?.failed_date)

sortedRows = sortedRows.sort((a, b) => a.failed_date?.localeCompare(b.failed_date));
J. Cutshall
  • 302
  • 3
  • 13
  • 2
    *"Because `arr?.[50]` checks if element 50 is nullish"*. No, it checks whether `arr` is nullish. `?.` always checks whether "the value before it" is null or undefined. But either way, the `sort` callback should always return a number and not `null`. You have to define some order for the elements if these objects are null or don't have that property. – Felix Kling Mar 24 '22 at 20:31
  • You can check each of these cases in your browser console, one at a time, for a better understanding. Note: `obj.method?.()` and `obj?.method()` are not the same. – Ry- Mar 24 '22 at 20:33

3 Answers3

3

Let's say you define variable like below

const variable = { value: 'test' };

then you want to access variable?.value it equals variable === null || variable === undefined ? undefined : variable.value.

Same with array.

Check typescript playground and see js output https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwXAnjAvDA2gXQNwBQBiyKA-AHRYCsADDkA

Pashozator
  • 46
  • 2
1

Basically, the ? in that context means optional chaining.

How it works is, for example, if you define an object like below, and you want to try and access the views property, it will throw an error.

const obj = { website: "stackoverflow.com", };
console.log(obj.views.toFixed(0)); // Error!

This is because you are trying to access a method off of undefined, which doesn't have anything.

To avoid this error, we can use optional chaining, like below.

const obj = { website: "stackoverflow.com", };
console.log(obj?.views?.toFixed(0)); // undefined

Optional chaining tells JavaScript to complete the method/read the key, but if it doesn't exist, instead of throwing an error, just return undefined.


It also works with arrays; the same way! If, say, index 78 doesn't exist, instead of throwing an error, it will just return undefined.

const arr = [1, 2, 3];
console.log(arr?.[78]?.toString());
Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33
0

To elaborate here, it is possible to stack multiple optional chaining operators as seen in OP's code a?.failed_date?.localeCompare(b?.failed_date) In these cases, it is not a question of which object key value will be checked. The code will be evaluated from left to right and if any of the object values are nullish then undefined will be returned.

Refer to the documentation for further understanding MDN Optional Chaining

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33371312) – Vojin Purić Dec 14 '22 at 08:14