Skip to content
Lew Dawson

JavaScript: "Falsy" Mishaps

TodayIRevisited, JavaScript, Node.js, falsy, Programming, coercion1 min read

I sometimes see web developers check for falsy values incorrectly in JavaScript. It's easy to get wrong. Here are a few common mistakes.

Missing Null

1if (myVariable === undefined)

This is probably the most frequent mistake I see. While this catches undefined properly, it doesn't guard against reference errors when myVariable is null. Unless you're explicitly trying to exclude null from your check, this will result in a null reference error if you try to access a property on myVariable.

Missing Undefined

1if(myVariable === null)

I don't see this as often, but it does happen. While this catches null properly, it does guard against reference errors when myVariable is undefined.

Excluding Too Much

1if(myVariable)

This check works fine if you don't want your logic to execute when you have null, undefined, false, zero (integer value), or empty string. The last two are sometimes overlooked as you may want your logic to execute when you have a zero or an empty string.

Capturing Null And Undefined In One

1if(myVariable == null)

If you're looking to checking for undefined and null in one statement, use type coercion to your advantage with the statement above. The statement above will evaluate to true when you have either. One of the few times I recommend using type coercion in JavaScript. Neat!

© 2021 by Lew Dawson. All rights reserved.