0

I'm refactoring some JS code as I meet this one. I need your advices regarding that "?." stuff.

Here it is:

const campaignId = action.notificationPayload?.campaign_id;

It's does something like this ternary:

const campaignId = action.notificationPayload ? action.notificationPayload.campaign_id : null

But, to assign a value I would rather not use a ternary and do something more like:

const campaignId = action.notificationPayload && action.notificationPayload.campaign_id

Or maybe check the truthiness of the value directly with:

const campaignId = action.notificationPayload.campaign_id && action.notificationPayload.campaign_id

In the previous samples, it's clear that ?. way is quite smaller without being less understandable. And it works ! I'm not sure it's quite good, especially when I need to lint all this stuff.

I know it's done in other languages but what do you think about JavaScript here?

Even got a second one, just for illustration:

if (action.result?.ordersTracking?.length > 0) {

We can argue first example regarding shortness of code, but this one is something else

Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
Kucinski
  • 1
  • 1
  • Null-safe Property Access, something like null coalesce operator for JavaScript. – Praveen Kumar Purushothaman Apr 16 '19 at 08:28
  • 1
    "And it works !" No it doesn't, not in any JavaScript that is currently implemented anywhere. It is [under proposal](https://github.com/tc39/proposal-optional-chaining), and it is available in some transpilers. I wish it was adopted, but it's still a way away. – Amadan Apr 16 '19 at 08:31

0 Answers0