JavaScript Essentials: Understanding ?? vs || Operators
Mastering JavaScript: Key Differences Between the ?? (Nullish Coalescing) and || (Logical OR) Operators
We recently wrote an article on JavaScript's new safe assignment operator (?=). Now, let’s explore how it differs from the ||
operator.
In JavaScript, handling "falsy" or empty values is essential for controlling application behavior, and both ||
(Logical OR) and ??
(Nullish Coalescing) operators serve this purpose with distinct applications.
||
Operator (Logical OR)
The ||
operator checks for falsy values such as 0
, false
, NaN
, ""
, null
, or undefined
. If it encounters any falsy value on the left, it returns the default value on the right.
Example:
let value = "";
let result = value || "Default"; // Output: "Default"
Here, since value
is an empty string (a falsy value), the operator provides the fallback "Default"
.
??
Operator (Nullish Coalescing)
The ??
operator only checks for null
or undefined
specifically. If the left operand is neither of these, it returns the original value even if it's falsy (like 0
or ""
).
Example:
let value = "";
let result = value ?? "Default"; // Output: ""
In this case, value
is an empty string, not null
or undefined
, so ??
keeps it as is without returning the fallback.
Choosing Between ||
and ??
Use ||
if you want to catch all falsy values and return a fallback. Use ??
when you only want to handle null
and undefined
, preserving other values like 0
or ""
.
Avoiding Common Pitfalls
With
||
: When a valid falsy value (e.g.,0
) is mistakenly overridden.
let price = 0;
let finalPrice = price || 100; // Output: 100, not 0 as intended
With
??
: When the fallback isn't triggered as expected for non-nullish falsy values.
let userInput = 0;
let output = userInput ?? "Default"; // Output: 0, not "Default"
Performance and Best Practices
The difference in performance between ||
and ??
is minor in typical scenarios, but they differ in that ||
checks each value until a truthy one is found, while ??
directly tests only for null
and undefined
.
Summary
||
: Handles all falsy values.??
: Handles onlynull
orundefined
.
Choosing the right operator depends on your intent: if only missing or null values matter, prefer ??
; for handling all falsy values, use ||
.
The example in the screenshot shows a double usage of the ||-operator: "... || 100 || 200", which makes no sense: the last part "|| 200" is superfluous in both lines as it will never be executed.