DEV Community

Joseph
Joseph

Posted on • Edited on

isNil - nullish coalescing ??

We have all been there. You need to check if something is null or undefined, but because false-like, falsy, values are a thing in JavaScript, 0, '', and false are also captured in your checks. You become frustrated, and, may end up writing a helper like this:

const exists = val => val !== null && val !== undefined
const isNil = val => val == null // actual lodash implementation
Enter fullscreen mode Exit fullscreen mode

In the first case, you have to be verbose, and you check if something is not null, nor, undefined.

In the second, well, there's just something strange about using loose equality in modern JavaScript (wouldn't blame you if you didn't notice), and here you actually check, if something is null or undefined.

Of course, both can be re-written:

const isNil = val => val === null || val === undefined
const exists = val => val != null
Enter fullscreen mode Exit fullscreen mode

Nowadays, the ?? nullish coalescing operator has been introduced, and it sits currently at stage-4, and is available in Chromium already. This operator checks for null and undefined in one go.

const str = (null || undefined) ?? 'default value'; // 'default value'
const num = 10 ?? 100 // 10
Enter fullscreen mode Exit fullscreen mode

Using this new operator you could write isNil and exists like this:

const isNil = val => val !== (val ?? !val);
const exists = val => val === (val ?? !val);
Enter fullscreen mode Exit fullscreen mode

There's nothing inherently better, about either of these approaches. Other than perhaps, showing off expanding your JavaScript knowledge.

I think the latter looks cleaner, maybe because it removes the need to explicitly write null, or undefined. Maybe because it uses flashy new language features?

One additional consideration, which I personally like, is that NaN, is also deemed to not exist, because NaN cannot be equal to itself.

Anyway, what do you think?

Top comments (0)