??
is part of ES 2021. Unless you have [Babel] integrated into your project, it will probably not work! Alternatively, just use your 'browser dev tools' (e.g. updated Chrome/FF/Edge).
Short-Circuiting of Logical Operator OR - ||
To appreciate the nullish coalescing operator - ??
, you should understand:
Specifically, the ||
short-circuit where if the left-hand side operand is 'truthy,' or can be implicitly coerced to be true
, the right-hand side is not evaluated.
For example, 3 || 4
, 4
will not be evaluated because, 3
, being a 'non-zero' number will be implicitly coerced to true
.
Similarly, in "mark" || "anonymous"
; "mark"
, being a non-empty string will be treated as true
and there is no need to consider "anonymous"
.
Summarily, if the left-hand side operand evaluates to true
- namely if it's not one of these...
0
""
null
undefined
false
...then the right-hand side operand will not be looked at.
const name = 'Mark Galloway';
// Since 'name' is a 'truthy' string, let's use that one!
const msg = `Hello, ${name || "anon"}`
Fine, But What About ??
It's quite simple really...it's all exactly the same as ππ½ but only null
and undefined
are considered falsey
Examples
As per MDN:
const foo = undefined ?? 'default string'; // 'foo' will be 'default string'
const buzz = null ?? 'Not null!'; // 'buzz' will be 'not null!'
const baz = 0 ?? 42; // 'baz' will be '0'
const bar = false ?? 42; // 'bar' will be 'false'
π€·π½ββοΈ - I don't really have much else to say on this one ποΈβπ¨οΈ. If you understand short circuiting of ||
then just trim the 'truthy' - 'falsey' rules down to only be: null
or undefined
.
Top comments (0)