JavaScript is a versatile and widely-used programming language, known for its concise syntax and powerful features. Two of its notable operators are the nullish coalescing operator (??) and the logical OR operator (||). While they may seem similar, they serve distinct purposes and have different behaviors. In this article, we’ll delve into the differences between these two operators and explore their use cases.
How Work „??” (Nullish Coalescing Operator)?
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
What is the Logical OR Operator (||)?
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
Key Differences Between ?? and ||
While both operators can be used to provide a default value, the key differences lie in their behavior:
- Null and undefined values:
??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). - Falsy values:
||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
Use Cases for ?? and ||
- Use
??when working with nullable or undefined values:??is ideal when you need to provide a default value for variables that might be null or undefined. - Use
||when working with falsy values:||is 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
Conclusion
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.
Dodaj komentarz