Andrew Kim
Andrew Kim's Blog

Andrew Kim's Blog

[Short JS Tip] Improved readability for falsy value check

Andrew Kim's photo
Andrew Kim
·Apr 22, 2022·

1 min read

Checking for a falsy value in JavaScript is where bugs can creep into your code easily. I recently came up with a good way of handling falsy value testing in a nice way.

if (!a) { /* do some stuff */ }

Does the internal logic get executed if?

a === 'false' || 'null' || 'undefined' || '0'
a === false || null || undefined || 0

Here is my approach:

if (['false', 'null', 'undefined'].includes(a)) { /* do stuff */ }

Happy Coding!

 
Share this