Nullish coalescing operator (??) vs OR(||)
(raw notes)
Nullish coalescing operator (??)
if the left side operand is NULL or UNDEFINED, the right-hand side operand is returned.
const foo = null ?? 'default string'; console.log(foo); // Expected output: "default string"
Nullish values are : NULL and Undefined
Falsey values, these below are the only falesy values in JS
Some more examples
false ?? "llo" -> since the left hand side operand is not a nullish value -> so the left hand side value is returned
\=> false
false || "llo" -> here the left side value is a falsey value so the right hand side value will be returned
\=>"llo"
Value | Type | Description |
null | Null | The keyword null — the absence of any value. |
undefined | Undefined | undefined — the primitive value. |
false | Boolean | The keyword false . |
NaN | Number | NaN — not a number. |
0 | Number | The Number zero, also including 0.0 , 0x0 , etc. |
-0 | Number | The Number negative zero, also including -0.0 , -0x0 , etc. |
0n | BigInt | The BigInt zero, also including 0x0n , etc. Note that there is no BigInt negative zero — the negation of 0n is 0n . |
"" | String | Empty string value, also including '' and `` . |
document.all | Object | The only falsy object in JavaScript is the built-in document.all . |
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
Subscribe to my newsletter
Read articles from Dheeraj Malik directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Dheeraj Malik
Dheeraj Malik
I write here to learn, feel free to correct.