0

I wanna do like this simply:

const someProp = someObj ? someObj.someProp : undefined;

In Ruby, we can use & operator.

some_prop = some_obj&.some_prop
Taichi
  • 1,787
  • 4
  • 19
  • 44
  • Possible duplicate of https://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null – Inus Saha Jun 21 '18 at 12:14
  • 1
    Possible duplicate of [How to determine if variable is 'undefined' or 'null'?](https://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null) – The Reason Jun 21 '18 at 12:16
  • [This article](https://www.beyondjava.net/elvis-operator-aka-safe-navigation-javascript-typescript) should be a good read for you to understand what your options are. – mhodges Jun 21 '18 at 15:40

2 Answers2

2

You are looking for the optional chaining operator which is also currently a stage 1 proposal:

const someProp = someObj?.someProp;

However, for the time being you could write a helper function:

function opt(obj, prop) {
  return obj ? obj.prop : null;
}

const someProp = opt(someObj, 'someProp');
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
1

There's no such operator currently in javascript.

There's a proposal for ?? to be added https://github.com/tc39/proposal-nullish-coalescing, but it's only at stage 1 meaning it's far from being in the language yet.

Axnyff
  • 8,235
  • 3
  • 31
  • 36