We often run into scenarios where we need to provide default values for variables. Two operators that can help with this are the logical OR (||) and the nullish coalescing (??) operators. While they might appear to behave similarly, they serve distinct purposes and understanding their differences is import for writing bug-free code.
An Example
Consider the following code snippet:
| |
In this example, the || operator is used to provide a default value if userPreference is null or undefined. The code works as expected and outputs "dark mode". Now, let’s tweak userPreference to an empty string:
| |
This output might be surprising because an empty string ("") is a valid value. However, the || operator considers it a falsy value and falls back to defaultPreference.
The ?? Operator
To address this issue, JavaScript introduced the nullish coalescing operator (??). This operator only falls back to the default value if the left-hand side is null or undefined.
Rewriting the previous example using ??:
| |
Here, theme correctly retains the value of userPreference since an empty string is neither null nor undefined.
Key Differences
Falsy Values:
||: Falls back if the left-hand side is any falsy value (e.g.,false,0,"",null,undefined,NaN).??: Falls back only if the left-hand side isnullorundefined.
Use Cases:
||: Use when you want to handle any falsy value.??: Use when you want to handle specificallynullorundefined.
Practical Examples
Handling User Input:
1 2 3 4 5 6 7 8let userInput = 0; let defaultValue = 10; let value = userInput || defaultValue; console.log(value); // Output: 10 value = userInput ?? defaultValue; console.log(value); // Output: 0When the user input is
0, which is a valid number, the||operator falls back todefaultValue, while the??operator correctly retainsuserInput.Configuration Settings:
1 2 3 4 5 6function getConfig(config) { return config.debug ?? true; } console.log(getConfig({ debug: false })); // Output: false console.log(getConfig({ debug: null })); // Output: trueThis example ensures that
debugis set totrueonly if it isnullorundefined, not just any falsy value.