Nullish Coalescing in JavaScript
Introduction
The Nullish Coalescing Operator (??
) in JavaScript helps to set default values when a variable is null or undefined. It is useful when you want to assign a fallback value only if the first value is missing.
- If the left-hand value is null or undefined, it returns the right-hand value.
- Otherwise, it returns the left-hand value.
Example Without ??
let onlineName = 'Spider Man';
let realName = 'Pratap';
let nameToUse = null;
// Traditional way
if (onlineName != null) {
nameToUse = onlineName;
} else {
nameToUse = realName;
}
console.log(nameToUse); // 'Spider Man'
Example Using ??
let onlineName = 'Spider Man';
let realName = 'Pratap';
// Using Nullish Coalescing Operator
let nameToUse = onlineName ?? realName;
console.log(nameToUse); // 'Spider Man'
How ??
Works with Numbers
let x = 5;
let y = 4;
x = x ?? y;
console.log(x); // 5 (since x is not null or undefined, it remains 5)
Difference Between ||
and ??
The ||
(OR) operator returns the right-hand value if the left-hand value is falsy (false, 0, '', null, undefined, NaN). But ??
only checks for null or undefined.
Example:
let value1 = 0 || 100;
console.log(value1); // 100 (because 0 is falsy)
let value2 = 0 ?? 100;
console.log(value2); // 0 (because 0 is not null or undefined)
Summary Table
Operator | Works with | Returns Right-Hand Value When |
---|---|---|
?? (Nullish Coalescing) | null or undefined | Left value is null or undefined |
ll (OR) | All falsy values | Left value is any falsy value (false, 0, '', null, undefined, NaN) |
Conclusion
- Use
??
when you only want to check for null or undefined. - Use
||
when you want to check for any falsy value.
This helps to write cleaner and more readable JavaScript code! 🚀