DEV Community

Julien Gonzalez
Julien Gonzalez

Posted on

The value of null (ish)

TL; DR: The absence of a thing is not the same as the thing being empty.

Say we represent a wallet with an array:

[1, 1, 2, 5, 10, 10] // 2 ⨉ £1, 1 ⨉ £2, …
Enter fullscreen mode Exit fullscreen mode

Now we need to decide when to fetch a wallet. I sometimes see this kind of logic:

if (!wallet?.length) {
  // fetch
}
Enter fullscreen mode Exit fullscreen mode

The problem here is that we equate the absence of a wallet with no money, potentially causing an infinite loop.

That is not to say that you can never consider those two things equally.

For instance, it's okay to restrict access to checkout if you either don't have a wallet or no money in it:

can_checkout = wallet?.length > 0
Enter fullscreen mode Exit fullscreen mode

However if you need to explain why a user can't check out (and you probably ought to) then those two things are very different:

checkout_err = ( wallet == null ? ERR_WALLET_NOT_FOUND
               : !wallet.length ? ERR_WALLET_EMPTY
                                : null )
Enter fullscreen mode Exit fullscreen mode

Top comments (0)