Abuse of the nullish coalescing operator in JS/TS

https://news.ycombinator.com/rss Hits: 2
Summary

If you've ever touched JavaScript or TypeScript, I'm sure you've seen something akin to user?.name ?? "" in your or someone else's codebase. It's a quick and dirty fix to combat the fact that the underlying type is string | undefined even though you might be convinced that it won't ever be undefined.But if that's the case, why do you treat "" as a valid option? By which I mean, if you truly believe that undefined isn't a valid state, why are you implementing a "solution" to that case by using the nullish coalescing operator ??? By doing this, you're opening up for the possibility of showing a UI where the name is "". Is that really a valid state for the UI? My philosophy here is that we should attempt to avoid implementing code which could lead to invalid UI states. That means that if the value of the right side of the nullish coalescing operator (what a mouthful) doesn't make sense as a value for the variable, then it shouldn't be there. It should rather be checked if the value is undefined, and throw an error, return an error modal/page/message, or by some other method, indicate that an error has occurred. Same goes for backend code — this isn't a problem limited to the realm of frontend. process.env.MY_ENV_VAR ?? "" is something I've seen time and again. If "" isn't a valid (in the sense of business logic) value for MY_ENV_VAR, i.e. a sane default, which is what I think it should be, then this should error. I'd much prefer to seeif (process.env.MY_ENV_VAR === undefined) { throw new Error("MY_ENV_VAR is not set") }Rather than seeing a runtime error since MY_ENV_VAR turned out to be an API key and "" wasn't good enough to call the API.Personally, I've come to see this ubiquitous string of symbols, ?? "", as the JS equivalent to .unwrap() in Rust, which for the uninitiated forcefully converts Option<T> to T — panic-ing if the Option was None. Translated to TS this roughly translates to making T | undefined into T and throwing an error that quits the program.In Rust,...

First seen: 2025-11-27 18:38

Last seen: 2025-11-27 19:38