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?
x
is an existing object for which you want to allow thesomething
property to be undefined. Hence, the correct syntax should bex.something?.foo
The syntax
x?.something.foo
means: allow an objectx
to be undefined, but if it isn't, return the value of the property chainsomething.foo
. Since in this casex
is defined, butx.something
isn't, you'll get an error (unless you usex?.something?.foo
).