Created
October 2, 2018 12:46
-
-
Save jackkoppa/0776d9a372adfa989d1234494b24929b to your computer and use it in GitHub Desktop.
Checking why null & undefined are the "right" falsy values to exclude during existence checks in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log( | |
'why `if (someVar != null)` will prevent type errors when we want to follow up with a check for a property \n', | |
`truthy value: ${'a string'.hasOwnProperty('test')}\n`, // executes | |
`empty string: ${''.hasOwnProperty('test')}\n`, // executes | |
`0: ${0['hasOwnProperty']('test')}\n`, // executes | |
`false: ${false.hasOwnProperty('test')}\n`, // executes | |
`NaN: ${NaN.hasOwnProperty('test')}\n` // executes | |
) | |
setTimeout(() => console.log(`null: ${null.hasOwnProperty('test')}\n` /* Type Error */ ), 500) | |
setTimeout(() => console.log(`undefined: ${undefined.hasOwnProperty('test')}\n` /* Type Error */ ), 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In doing a code review, found another justification for why
if (someVar != null)
is one of the better existence checks in JavaScript (original recommendation on SO here, tl;dr: will only catchnull
andundefined
).When you'll be following up the existence check by accessing a property, or checking if a property exists,
null
andundefined
are indeed the only 2 falsy values to throw type errors.