— TodayIRevisited, JavaScript, Node.js, falsy, Programming, coercion — 1 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.
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.
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.
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.
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!