Appearance
Logical Operators
JavaScript's logical operators (|| and ??) evaluate expressions and return one of their operands. While they're commonly used in boolean logic, they're also frequently used as a shorthand for selecting values, particularly for providing defaults.
Logical OR (||)
The logical OR operator (||) evaluates the left side first. If that value is falsy (like undefined, null, 0, or ""), it returns the right side. This makes it useful for providing default values, but be careful - it considers ALL falsy values as triggers for the default:
js
let v;
v = v || 456; // undefined || 456 -> returns 456 (common and expected)
let v = 0;
v = v || 456; // 0 || 456 -> returns 456 (might be unexpected!)Nullish Coalescing (??)
The nullish coalescing operator (??) was introduced to fix this common problem with ||: sometimes you want to keep falsy values like 0 or "". The ?? operator only triggers the default value for null or undefined:
js
let v = 0;
v = v ?? 456; // 0 ?? 456 -> returns 0 (preserves the zero default)💡 Rule of thumb: Use
??when0or""are possible and expected values in your code. Use||when you want to catch all falsy values.
Common Use Case: Function Parameters
Logical operators are often used as a concise way to handle default parameter values in functions. Here's a comparison:
js
// Traditional if statement
function greet(name) {
if (name === undefined) {
name = "Guest";
}
return `Hello, ${name}!`;
}
// Using || operator (catches all falsy values)
function greet(name) {
name = name || "Guest";
return `Hello, ${name}!`;
}
// Using ?? operator (only catches null/undefined)
function formatNumber(num) {
num = num ?? 0; // Preserves 0 if passed explicitly
return num.toFixed(2);
}The logical operator syntax is more compact and is a very common pattern in JavaScript code. The choice between || and ?? depends on whether you want to treat empty strings and zero as valid inputs.
External Resources