Re:Modern Javascript: Everything you missed over the last 10...
by Cyberdog on Saturday May 15, 2021 @01:18PM
(#27167039)
I didn't know JS had `??` for a nil coalescing operator, or, more specifically, I thought it already had `||` for that purpose, since I've been using it for that for a decade or so without any problems. How do the two differ?
[ Parent
| on HN ]
Re:Modern Javascript: Everything you missed over the last 10...
by TooCleverByHalf on Saturday May 15, 2021 @01:21PM
(#27167070)
?? - returns right side operand if left side operand is null or undefined
|| - returns right side operand if left side operand is any falsy value
Re:Modern Javascript: Everything you missed over the last 10...
by qsort on Saturday May 15, 2021 @01:22PM
(#27167085)
> 0 ?? 1
0
> 0 || 1
1
Re:Modern Javascript: Everything you missed over the last 10...
by nailer on Saturday May 15, 2021 @01:30PM
(#27167165)
I like this answer because it’s practical. Eg score 0 is a different thing from score undefined (which means you don’t know the score).
Re:Modern Javascript: Everything you missed over the last 10...
by beardyw on Saturday May 15, 2021 @01:28PM
(#27167133)
I think ?? only acts on null or undefined, || acts on any falsey value.
Re:Modern Javascript: Everything you missed over the last 10...
by frosted-flakes on Saturday May 15, 2021 @01:24PM
(#27167100)
?? only coalesces nullish values (hence the name), which only includes null and undefined. || coalesces falsey values, which include false, 0, and empty strings. || might work most of the time, but it requires extra checks when falsey values are valid.