Blog

OR (||) vs Nullish Coalescing (??) in TypeScript

Sep 29, 2021    ●   
Shivang Zala

The operator signifies an operation to be performed on value(s). The value(s) on which the operation is performed are called operand(s). TypeScript provides many operators such as +, -, *, /, ++, –, >, <, ==, ===, &&, || etc.

TypeScript 3.7 introduced a new operator called the “Nullish Coalescing (??)”. It is quite a handy replacement for the isNullOrUndefined() function. However, it’s very common to get it confused with the logical OR (||) operator due to the similar nature of both the operators.

We’re gonna understand the thin line which differentiates both with a few examples in this article.

OR (||) Operator:

The logical OR (||) operator checks for the falsy values. If the left-hand side value is falsy, the right-hand side value is returned. Falsy values include null, undefined, 0, false, NaN, “” etc. For example,

const a = 3;
const b = 3;

console.log((a - b) || "Error")

Output: "Error"

This may be unintended in most of the cases as 0 might be useful in further logic. So, the Nullish Coalescing (??) operator helps us in resolving these types of scenarios.

Nullish Coalescing (??) Operator:

The Nullish Coalescing (??) operator works in similar manner as the OR (||) operator. However, the difference is that it only checks for nullish values. Nullish values include null and undefined. If the left-hand side is nullish, the right-hand side value is returned.

const a = 3;
const b = 3;

console.log((a - b) ?? "Error")

Output:  0

Precedence of ?? operator compared to similar operators:

AND (&&) > OR (||) > Nullish Coalescing (??) > Ternary (.. ? .. : ..)

Difference between OR (||) and Nullish Coalescing (??):

OR (||) Nullish Coalescing (??)
Returns the right-hand side value if the left-hand side value is falsy Returns the right-hand side value if the left-hand side value is nullish
Falsy values include null, undefined, 0, false, NaN, “” etc Nullish values include null and undefined
Higher precedence than ?? Lower precedence than ||
Preferable to use with boolean values Preferable to use with non-boolean values

By Shivang Zala

A full-stack developer at Altum having expertise in languages like C#, Angular, Vue and Java. Development is my passion and it motivates me to resolve people’s problems using my skills. A big time gamer and a foodie in free time.