In today's edition of Adventures in Legacy Code, I came across the following:
if(
tokenInfo &&
tokenInfo !== undefined &&
tokenInfo !== null &&
tokenInfo !== ""
)
I get it—we need to prevent things from going wrong, but the sight of it brings helicopter parenting to mind. Also, it's not really null-checking, but also undefined- and empty-string-checking. This is another benefit you can gain from TypeScript—the peace of mind that it won't compile if you're sending the wrong information.
I'm taking Patricia Aas's advice, and I'm choosing to frame this in the mental model of the developers who created it at time it was created rather than being overly critical. It's just an opinion, after all!
What are your thoughts? How are you checking for empty or null values? Bonus if you comment with examples in other programming languages!
Top comments (5)
It's more a bright exemple of how to make simple things looks complicated because in javascript
if(tokenInfo)
will check if variable is either :""
Looking at this block of code...
If the first check...
... is
undefined
,null
, or""
, or any other falsy valuue... then the if will short circuit and not perform any of the other checks. This means it is impossible for thetokenInfo !== undefined
check (and others) to ever evaluate to true.So that block of code is identical to this block:
The other checks are unnecessary as they won't change the function at all.
I think the concepts of truthy and falsy values is both the best and worst thing about javascript. I love it when it works with me and hate it with my entire heart when it doesn't ¯\_(ツ)_/¯
With that said I would have written the snippet in the example as
if (tokenInfo)
:)As others have said,
if (value)
will already check for empties and nulls and stuff.However, people (aka me) tend to forget or get confused about how truthy and falsy work in Javascript, or sometimes I need to check that a variable is not
null
orundefined
, but0
is an acceptable value. Therefore, I like to create helper functions that make the exact check I want explicit.Here's an example of what I mean.
Now it's obvious that I'm checking whether
tokenInfo
is defined (and that means at this point it could be not), and whether it is empty.Then I can use the classic
if (tokenInfo)
for actual boolean checks only and avoid having to remember whether it is a boolean check or a truthy/falsy check.Never use null unless you're trying to express an actual null value.
Checking for !variable is usually a sufficient check for undefined unless the variable is boolean.
Never use == for comparison unless you have a deep understanding of what it's comparing.
If implicit type coercision is confusing, use Typescript.