10

I was looking through a code and I came across this:

{{abc?.xvy=== tyu?abc?.xz:abc?.xz}}

I am unable to understand meaning of this expression. I know that it is Null-safe property access but I am bit confused about the chaining. Any help is much appreciated

Apurva Pathak
  • 456
  • 6
  • 16

3 Answers3

8

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
CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
5

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

Vishal Rajole
  • 1,329
  • 1
  • 12
  • 17
5

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.

Alex Park
  • 394
  • 3
  • 10