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
  • 2,297
  • 6
  • 25
  • 47
  • 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
  • 795,719
  • 175
  • 1,089
  • 1,143
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
  • 9,213
  • 4
  • 33
  • 37