1

I have tried this syntax in VSCode and Coderpad (both use Node version 16.4).

let x = {}
x?.something.foo

As far as my understanding goes, this code shouldn't throw an error now, but return undefined. The feature optional chaining should be available in Node v14+ but for some reason it doesn't work in my VSCode and also in Coderpad.

Thought why?

SrdjaNo1
  • 755
  • 3
  • 8
  • 18

1 Answers1

2

x is an existing object for which you want to allow the something property to be undefined. Hence, the correct syntax should be x.something?.foo

The syntax x?.something.foo means: allow an object x to be undefined, but if it isn't, return the value of the property chain something.foo. Since in this case x is defined, but x.something isn't, you'll get an error (unless you use x?.something?.foo).

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • `... you'll get an error (unless you use x?.something?.foo)` thats not true as long as x is defined. The `?` after the `x` is not necessary. `x.something` will be undefined and `x.something.foo` will be an error. `x.something?.foo` will be undefined. – aProgger Jun 20 '23 at 09:47
  • @aProgger I probably should have written it down more clearly. What I mean is that using `x?.something.foo` will throw an error if `x` is defined but `x.something` isn't (as in OP's example). Using `x?.something?.foo` would be useful if `x` or `x.something` could be undefined. – robertklep Jun 20 '23 at 10:37