Nullish coalescing operator (??) vs OR(||)

Dheeraj MalikDheeraj Malik
2 min read

(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"

ValueTypeDescription
nullNullThe keyword null — the absence of any value.
undefinedUndefinedundefined — the primitive value.
falseBooleanThe keyword false.
NaNNumberNaN — not a number.
0NumberThe Number zero, also including 0.0, 0x0, etc.
-0NumberThe Number negative zero, also including -0.0, -0x0, etc.
0nBigIntThe BigInt zero, also including 0x0n, etc. Note that there is no BigInt negative zero — the negation of 0n is 0n.
""StringEmpty string value, also including '' and `` .
document.allObjectThe only falsy object in JavaScript is the built-in document.all.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing

0
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.