-3

Is ?. a valid operator in Typescript or Javascript?

I have seen code like below:

const var1 = obj1?.innerObj1?.somePropVal; 

When I try this in the chrome console, I get an error if obj1 is undefined. Not sure whether this kind of code would work.

Let me know if I am missing something.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
cethie
  • 49
  • 3
  • 8
  • 1
    optional chaining (?.) is valid in both TypeScript and relatively recently also vanilla JS. The above code should work in chrome if you're using a somewhat up to date chrome – Nick Parsons Oct 05 '21 at 08:56
  • 1
    What do you mean with _"obj1 is undefined"_? I get an error when obj1 is not defined but I don't get an error when it's undefined. `undefined` and "not defined" are two different things in JavaScript. You can't use optional chaining to catch `ReferenceError`. – jabaa Oct 05 '21 at 08:58
  • Are you talking about ternary operator ( ? : ) ? – itiDi Oct 05 '21 at 08:59
  • 1
    @itiDi: OP is clearly not talking about that. `?.` is mentioned in the title, in the text and in the code example. It's highly unlikely that they mistyped 3 times and didn't notice. Also if you replace `?.` with `?:` in the sample, it makes absolutely no sense. – Joachim Sauer Oct 05 '21 at 09:01
  • @itiDi I was talking about the optional chaining operator. I got the required explanation from other comments. Thank you. – cethie Oct 05 '21 at 09:05
  • 1
    @NickParsons I was able to read up on "optional chaining" and understand. Thanks a ton for helping with the term. That was the key. – cethie Oct 05 '21 at 09:07

1 Answers1

3
const var1 = obj1?.innerObj1?.somePropVal;

is the same as:

const var1 = obj1 && obj1.innerObj1 ? obj1.innerObj1.somePropVal : undefined;
Old Geezer
  • 14,854
  • 31
  • 111
  • 198