Both Nullish Coalescing Operator (??) and Logical OR (||) operator are often used in JavaScript to provide a default value to variables. These help us prevent any unexpected behavior in our code.
Nullish Coalescing Operator (??): This is specifically designed to handle situations where the left operand might be unintentionally left unassigned (null) or missing a a value (undefined). It only considers null and undefined as nullish values.
Logical OR (||): This is useful when you want a default value if the left operand is any falsy value. This includes null, undefined, 0, empty string (""), false, and NaN.
Lets take these examples :
- If you want to check and avoid printing empty values, use the Logical OR Operator (||).
console.log("" || "Hello")
// "Hello"
console.log("" ?? "Hello")
// ""
- If 0 or Boolean false is a valid return value in your use-case, use ?? (Nullish coalescing).
console.log(0 || "Hello")
// "Hello"
console.log(0 ?? "Hello")
// 0
console.log(false || "Hello")
// "Hello"
console.log(false ?? "Hello")
// false
console.log(0 || "Hello")
// "Hello"
console.log(0 ?? "Hello")
// 0
- If you are only checking for undefined or null, you can go for either one of them :
console.log(undefined ?? "Hello")
// "Hello"
console.log(undefined || "Hello")
// "Hello"
console.log(null ?? "Hello")
// "Hello"
console.log(null || "Hello")
// "Hello"
Top comments (6)
Yea, it´s tricky. Thank you for your examples!
Welcome :)
Good 👍
Thanks!
Performance?
?? is a little costlier than || as it would be expanded when it is being Transpiled (Eg : Babel). However, for smaller conditions, ?? is good enough
dev.to/tusharshahi/cost-of-unneces... - Found this article good