Nullish coalescing operator ??

A Simple Guide to understanding the basics (with examples)

The Nullish Coalescing operator (??) returns the defined value of the two expressions

The result of a ?? b is:

  • If a is undefined or null then b
  • If a holds a defined value then a

Remember: 0 is evaluated as falsy but ?? specifically looks for undefined or null only.

Syntax

leftExpression ?? rightExpression

The right-hand expression is returned only if the left-hand expression is null or undefined

Some Examples

const val = null ?? "Some value";
console.log(val); // Output: "Some value"

In the above example, "Some value" is assigned to val because the left-hand expression evaluates to null.

const val = 0 ?? 30;
console.log(val); // Output: 0

Since 0 is neither null nor undefined, hence val is assigned 0 instead of 30.

Nullish coalescing (??) seems quite similar to the || (OR) operator, isn't it?

Well, the answer is No. Let's see how!

Comparison with logical || (OR) operator

const valA = "" ?? "default for A";
console.log(valA); // Output: ""

const valB = "" || "default for A";
console.log(valB); // Output: "default for A"

In the first console.log() statement empty("") string is returned because the ?? operator "" doesn't evaluate to null or undefined.

In the second statement "default for A" is returned because the || operator treats "" as false and hence does a logical OR operation. false || "default for A" evaluates to "default for A"

const valC = 0 ?? 20;
console.log(valC); // Output: 0

const valD = 0 || 20;
console.log(valD); // Output: 20

Similarly, in the first statement since 0 is neither null nor undefined valA is assigned to 0 (left-hand expression).

However, in the second statement 0 evaluates to false, and false || 20 results in 20 being assigned to valD.


Thank you for reading.

I hope this has been helpful. Let me know your feedback in the comments. I would love to connect with you at Twitter | LinkedIn | GitHub

No Comments Yet