What is the obj?.prop syntax in javascript?
Its new ES proposal called "optionals" for safe check reading for object properties. Above expression is equivalent to:
(abc && abc.xvy) === (tyu) ? (abc && abc.xz) : (abc && abc.xz)
You can find more details here: https://github.com/davidyaha/ecmascript-optionals-proposal
It's called Null Propagation Operator.
We can think of each ?. operator as a short circuit where "if the expression up until this point is null or undefined, then the whole expression evaluates to undefined". We could also optionally call functions.
This looks to be an example of the optional chaining proposal, which is still very much a work in progress (only at Stage 1). It's not actually implemented in vanilla JS environments yet. Using
obj?.prop
means: if obj
is undefined or null, the expression evaluates to undefined
. But otherwise, it will evaluate to the prop
property on the object. This is syntax sugar for
obj && obj.prop
(using just obj.prop
alone will throw if obj
is undefined or null)
So, your
abc?.xvy=== tyu?abc?.xz:abc?.xz
will evaluate to true
if the nested value abc?.xvy
is equal to the nested value abc?.xz
- or, it will evaluate to true
if at least one of the nested values doesn't exist, and the other is undefined
.
Spaced out for easier reading:
abc?.xvy === tyu
? abc?.xz
: abc?.xz
As you can see, both ?
and :
expressions are the same, making the conditional operator unnecessary here. An equivalent test (assuming that referencing tyu
doesn't throw) would be
abc?.xvy === abc?.xz