Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the obj?.prop syntax in javascript? [duplicate]

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

like image 703
Apurva Pathak Avatar asked Feb 05 '19 06:02

Apurva Pathak


3 Answers

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.

like image 70
Alex Park Avatar answered Oct 01 '22 20:10

Alex Park


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
like image 34
CertainPerformance Avatar answered Oct 01 '22 20:10

CertainPerformance


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

like image 28
Vishal Rajole Avatar answered Oct 01 '22 21:10

Vishal Rajole