2

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.

4
  • 5
    Documentation link: Nullish coalescing operator
    – DBS
    Commented Jan 26, 2022 at 11:59
  • 2
    This has nothing to do with react. Commented Jan 26, 2022 at 11:59
  • Note that ?? is not a ternary operator. It's a binary operator - it has two operands. "Ternary" just means "has three operands".
    – Jon Skeet
    Commented Jan 26, 2022 at 12:01
  • 1
    This page gives you a live explanation on each JS operator: joshwcomeau.com/operator-lookup
    – maxpsz
    Commented Jan 26, 2022 at 12:04

2 Answers 2

4

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

2
  • The other way around for ?? I think? Commented Jan 26, 2022 at 12:34
  • Of course - 🤦‍♂️ - got it mixed up when I was writing! Corrected the post accordingly. Commented Jan 26, 2022 at 13:36
0

First, as already pointed out, this isn't specific to React, but plain JavaScript syntax.

Let's break it down.

Optional Chaining ?.

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.

Nullish coalescing operator (??)

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.

Final output: Strict Equality Comparison

const output = result2 === 0

The expression evaluates to true if result2 is strictly equal to the numeric value 0. Also read the docs here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.