JavaScript
January 27, 2025
Sebastian
Javascript’s nullish coalescing operator ??
and logical OR operator ||
serve distinct purposes despite seeming similar. This article explores their differences and use cases.
The nullish coalescing operator ??
is a binary operator that returns the first operand if it’s not null or undefined, and the second operand if it’s null or undefined. It’s a shorthand way to provide a default value when working with nullable or undefined variables.
const name = null;
const fullName = name ?? 'Unknown';
console.log(fullName); // Output: Unknown
The logical OR operator ||
is a binary operator that returns the first truthy value it encounters. If the first operand is falsy, it returns the second operand.
const name = '';
const fullName = name || 'Unknown';
console.log(fullName); // Output: Unknown
While both operators can be used to provide a default value, the key differences lie in their behavior:
??
)only returns the second operand if the first operand is null or undefined. In contrast, ||
returns the second operand if the first operand is falsy (e.g., empty string, 0, false).
||
)treats falsy values as „false” and returns the second operand. ??
doesn’t consider falsy values as „false” and returns the first operand if it’s not null or undefined.
const name = '';
const fullName1 = name ?? 'Unknown';
console.log(fullName1); // Output: ''
const fullName2 = name || 'Unknown';
console.log(fullName2); // Output: Unknown
??
when working with nullable or undefined valuesis ideal when you need to provide a default value for variables that might be null or undefined.
||
when working with falsy valuesis suitable when you need to provide a default value for variables that might be falsy (e.g., empty string, 0, false).
// Using ?? with nullable values
const user = { name: null, age: 25 };
const fullName = user.name ?? 'Unknown';
console.log(fullName); // Output: Unknown
// Using || with falsy values
const name = '';
const fullName = name || 'Unknown';
console.log(fullName); // Output: Unknown
In conclusion, while both ??
and ||
can be used to provide a default value, they have distinct behaviors and use cases. Understanding the differences between these two operators will help you write more concise and readable JavaScript code.