Member-only story
Nullish Coalescing Operator (??) — ? vs ?? — ?? vs || — Javascript
It is a logical operator that operate on two values and left side value is returned if not null or undefined, if not right side way returned
const tax = response.tax ?? 5
Consider response as the API response, and if tax is undefined
or null
, 5 will be the tax, on the other hand if we get tax from the response that will be used.
? vs ??
Don’t confuse with ?
(Optional chaining) with this operator.
const tax = response?.tax ?? 5
?
— Only if response
object is defined, tax will be accessed to prevent errors and breaking the code (null checking)
??
— If response.tax
is defined, then that will be returned, if not default value of 5
?? vs ||
||
will be a problem when operating around 0
, because 0
is considered false that value cannot be selected
So this operator is ideal choice when you want to have a default value when something is undefined
or null