3 ms·
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 tha
by Cyberdog 5y ago
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?
- TooCleverByHalf 5y ago?? - returns right side operand if left side operand is null or undefined || - returns right side operand if left side operand is any falsy value
- luftbbb 5y agoNull coalescing is far more concise and basically offers a retroactive step in the case of a null. It's entirely different from using an OR condition
- qsort 5y ago> 0 ?? 1 0 > 0 || 1 1
- nailer 5y agoI 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).
- frosted-flakes 5y ago?? 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.
- beardyw 5y agoI think ?? only acts on null or undefined, || acts on any falsey value.