READ TIME - 2 MINUTES
Today, we're going to analyze the difference between the || (logical OR) and ?? (nullish coalescing) operators in JavaScript, focusing on where and when to use each one.
Understanding the difference is crucial for writing clean, predictable code. Confusing these two can lead to unexpected behavior and subtle bugs in your applications.
The mistake many developers make is assuming that both operators behave the same way when handling null
, undefined
, or falsy values like 0
or ''
(empty string).
Understanding the distinction between ||
and ??
is essential for writing code that behaves exactly as you intend when setting default or fallback values.
In JavaScript, both || and ?? are used for assigning default values, but they handle falsy values differently:
|| (Logical OR) considers any falsy value (like
0
,''
,false
,null
,undefined
,NaN
) and triggers the fallback.?? (Nullish Coalescing) only considers
null
orundefined
as triggers for the fallback. It's helpful when you want to avoid overriding useful falsy values like0
or''
.
Key Takeaways
Use
||
when you want to fall back if any falsy value is encountered.Use
??
when you only want to fall back fornull
orundefined
.Misusing these operators can lead to incorrect assumptions about your code’s logic.
Practical Examples
Using ||
In this example, because an empty string is a falsy value, ||
treats it the same as null
or undefined
and applies the fallback.
Using ??
Here, the empty string is preserved because ??
only considers null
or undefined
for fallback logic.
Handling Zero with ??
and ||
If you use ||
, you mistakenly trigger the fallback when count is 0
. However, with ??
, the 0
is kept since it’s a valid value, not null
or undefined
.
Conclusion
Understanding the difference between ||
and ??
helps you write more predictable and maintainable code.
Use || when you want a general fallback for any falsy value, and ?? when you only want to handle cases of null or undefined. With this knowledge, you can avoid subtle bugs and keep your logic crystal clear.
See you next Saturday!
Keep up the great work! :)
Very informative, thanks for sharing!