Have you ever encountered a situation where your JavaScript code returned unexpected results just because you used the wrong operator? Choosing the right operator in JavaScript is crucial for writing accurate, efficient, and bug-free code.
The Logical OR (||) and Nullish Coalescing (??) operators may look similar at first glance, but they behave very differently—especially when it comes to handling null, undefined, and other "falsy" values. Are you sure you're using them correctly? Let’s dive in with codetuthub to better understand when to use each one through real-world examples.
Logical OR Operator (||)
The Logical OR operator (||) is a familiar logical operator in many programming languages. In JavaScript, it's used not only in boolean expressions but also for assigning default values. When used in this context, || returns:
- The left-hand operand if it is truthy.
- The right-hand operand if the left-hand operand is falsy.
Falsy values in JavaScript include:
falsenullundefined0NaN""(empty string)
Let’s look at a few examples:
let username = "";
let defaultUsername = username || "Guest";
console.log(defaultUsername); // Output: "Guest"
let count = 0;
let displayCount = count || 1;
console.log(displayCount); // Output: 1
let isAdmin = null;
let role = isAdmin || "user";
console.log(role); // Output: "user"In the examples above, the || operator works well when assigning default values in the case of null or undefined. However, problems arise when you want to treat values like 0 or "" as valid rather than as missing.
Example:
let a = 0;
let b = 10;
let value = a || b;
console.log(value); // Output: 10Since a is 0 (a falsy value), || returns b, which is 10.
Nullish Coalescing Operator (??)
The Nullish Coalescing operator (??) was introduced in ECMAScript 2020 to address the limitations of the || operator. ?? only considers two values as "nullish":
nullundefined
When used, the ?? operator returns:
- The left-hand operand if it is not
nullorundefined. - The right-hand operand otherwise.
Let’s revisit the same examples using ??:
let username = "";
let defaultUsername = username ?? "Guest";
console.log(defaultUsername); // Output: ""
let count = 0;
let displayCount = count ?? 1;
console.log(displayCount); // Output: 0
let isAdmin = null;
let role = isAdmin ?? "user";
console.log(role); // Output: "user"As you can see, ?? behaves differently from || in cases involving an empty string ("") or zero (0). It only replaces the value when the left-hand operand is truly null or undefined.
Example:
let a = 0;
let b = 10;
let value = a ?? b;
console.log(value); // Output: 0Here, a is 0, which is falsy but not null or undefined, so ?? returns a.
Key Differences Between || and ??
1. Handling Falsy Values:
||returns the second operand if the first is any falsy value (false,0,NaN,"",null,undefined).??returns the second operand only if the first isnullorundefined. Other falsy values likefalse,0, or""are considered valid.
2. Use Cases:
- Use
||when you want to provide a default for any falsy value. - Use
??when you want to preserve valid falsy values and only handlenullorundefined.
3. Comparison Examples:
// With Logical OR (||)
let foo = 0;
let bar = "Hello";
console.log(foo || bar); // Output: "Hello"
// With Nullish Coalescing (??)
let foo2 = 0;
let bar2 = "Hello";
console.log(foo2 ?? bar2); // Output: 0In the first example, 0 is falsy, so || returns "Hello". In the second, ?? preserves 0 because it is not null or undefined.
When to Use Which Operator
Choosing between || and ?? depends on your use case and logic.
Use || when:
- You want a default value for any falsy input, such as in user interfaces, display defaults, or condition checks.
Use ?? when:
- You want to default only when the input is actually missing (
nullorundefined). - You need to preserve values like
0,false, or empty string, which are considered meaningful in your logic.
Real-World Example:
Imagine receiving configuration from an API. The timeout value may be a number or may be missing (null or undefined). If it’s 0, it means "no timeout." In this case, use ?? to assign a default only if the value is truly absent:
const configFromApi = {
apiUrl: "https://api.example.com",
timeout: 0
};
const timeoutValue = configFromApi.timeout ?? 5000;
console.log(`Timeout value: ${timeoutValue}`); // Output: 0
const anotherConfig = {
apiUrl: "https://api.example.com"
};
const anotherTimeoutValue = anotherConfig.timeout ?? 5000;
console.log(`Another timeout value: ${anotherTimeoutValue}`); // Output: 5000If we had used ||, the timeout 0 would be treated as falsy and wrongly replaced by 5000.
Conclusion
The Logical OR (||) and Nullish Coalescing (??) operators are both powerful tools for assigning default values in JavaScript. However, their behavior and intent differ:
- Use
||when any falsy value should trigger a fallback. - Use
??when onlynullorundefinedshould trigger a fallback.
Choosing the right operator not only makes your code more robust but also prevents hidden logic errors. Always ask yourself: "Is my falsy value (like 0, false, or "") valid in this context?" If yes, then consider using ??.
Happy coding JavaScript the right way with codetuthub!








