How to Use Nullish Coalesce for Real Defaults

?? only triggers on null/undefined. 0 and '' stay. || lies.

#javascript #nullish #coalesce #defaults #howto

https://www.youtube.com/watch?v=MA8lRIqoPNk

How to Use Nullish Coalesce for Real Defaults #howto

YouTube
Ah, the programmer's favorite pastime: blaming the '??' for their own poor life choices. 🤦‍♂️ The #nullish #coalescing operator is apparently the root of all evil, because clearly, #type #safety is just too mainstream. 🤷‍♀️ But fear not! Our brave author is here to save the day with a *comprehensive* #blog #post, because who doesn't love a good ol' #JavaScript sermon? 📜💻
https://fredrikmalmo.com/blog/js-ts-nullish-empty-string-coalescing #programming #humor #HackerNews #ngated
Invalid values and the nullish coalescing operator in JavaScript

After working as a JS/TS developer for quite some years I've grown quite used to seeing || "" or ?? "" strewn around codebases as a quick fix to "remove" nullability, usually due to some value which you assume is set, but can't "prove" type-wise. I think this is a code smell, and I generally think it's not the right solution. In this post I try to explain why I don't think so, and provide some patterns that could help combat the downsides introduced by this pattern.

Fredrik's Homepage
Invalid values and the nullish coalescing operator in JavaScript

After working as a JS/TS developer for quite some years I've grown quite used to seeing || "" or ?? "" strewn around codebases as a quick fix to "remove" nullability, usually due to some value which you assume is set, but can't "prove" type-wise. I think this is a code smell, and I generally think it's not the right solution. In this post I try to explain why I don't think so, and provide some patterns that could help combat the downsides introduced by this pattern.

Fredrik's Homepage
Logical nullish assignment (??=) - JavaScript | MDN

The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined).