DEV Community

Discussion on: Null-checking in JavaScript

Collapse
 
avalander profile image
Avalander

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 or undefined, but 0 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.

const exists = value => value != null // checks for null and undefined.

const isEmpty = value => value.length > 0

if (exists(tokenInfo) && !isEmpty(tokenInfo)) { ... }

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.