
Difference between ?? and || in typescript
In TypeScript, ??
and ||
are both operators used for handling default values or fallback values, but they serve slightly different purposes:
- Nullish Coalescing Operator (
??
):
The nullish coalescing operator ??
is used to provide a default value only when the operand on its left-hand side evaluates to null
or undefined
. It specifically checks for null
or undefined
, but not for other falsy values like 0
, ""
, false
, etc.
Here’s how it works:
typescriptCopy codeconst value = null ?? 'default';
console.log(value); // Output: 'default'
In the above example, since null
is on the left-hand side of ??
, the default value 'default'
is used.
- Logical OR Operator (
||
):
The logical OR operator ||
is a boolean operator. It returns the value of its first operand if that operand evaluates to true
. Otherwise, it returns the value of its second operand.
Here’s how it works:
typescriptCopy codeconst value = null || 'default';
console.log(value); // Output: 'default'
In this example, since null
evaluates to false
in a boolean context, the second operand 'default'
is returned.
In summary:
??
: Checks fornull
orundefined
specifically.||
: Checks for any falsy value (null
,undefined
,0
,""
,false
, etc.), but not specificallynull
orundefined
.