The ??
(nullish coalescing) and ||
(logical OR) operators in JavaScript are used to provide a default value when the expression on the left-hand side is not provided. They are helpful when handling cases where a value might not exist or is falsy, and you want to ensure a fallback is provided.
What Does The ?? Operator Means: The ?? operator is used to provide a default value when the expression on the left-hand side is either null
or undefined
, but allows other falsy values like 0
, false
, or ''
(empty string) to remain. This simple means that even if the value of the left-hand side is 0, false, of '' ,
the result will return the left hand side.
let value = 0; const testValue = value ?? 'Default Value' output : 0
What Does The ||
Operator Means: The ||
is quite similar to the ?? operator, but what distinguish the ??
from the ||
is that it checks for all falsy values.const count = 0; const testCount = count || 10; output: 10
(because 0 is falsy).
Tip: Use ??
when working with APIs, optional parameters, or dynamic data that may not always be defined. You can provide a fallback without affecting valid falsy values like false
or an empty string.