i have code like below,
const output = (data?.item?.someItem?.count ?? 0) === 0;
what is the value of output in this case what does ?? in above line mean. could someone help me understand this line of code.
I am new to programming. thanks.
i have code like below,
const output = (data?.item?.someItem?.count ?? 0) === 0;
what is the value of output in this case what does ?? in above line mean. could someone help me understand this line of code.
I am new to programming. thanks.
The "optional chaining operator" ?.
gets a property of an object, if that exists and the "nullish coalescing operator" ??
acts very similar to the ||
operator: It returns the first operand if it is NOT null
or undefined
, otherwise it returns the second one.
The ||
behaves slightly differently: It will return the seond operand if the first operand is "falsey" (i. e. 0
or false
will also trigger the second operand to be returned).
You can find more details here: MDM Web Docs - Operators
First, as already pointed out, this isn't specific to React, but plain JavaScript syntax.
Let's break it down.
const result1 = data?.item?.someItem?.count
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
So even if data
, item
or someItem
is undefined or null, you could still use this statement without generating an error, but you would simply get an undefined
value.
Read more about it in the docs here.
const result2 = result1 ?? 0
As described in the docs:
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
In your case, the expression will return 0
if element
is null or undefined, otherwise it returns element
.
const output = result2 === 0
The expression evaluates to true if result2
is strictly equal to the numeric value 0
. Also read the docs here.