Skip to content

Instantly share code, notes, and snippets.

@jackkoppa
Created October 2, 2018 12:46
Show Gist options
  • Save jackkoppa/0776d9a372adfa989d1234494b24929b to your computer and use it in GitHub Desktop.
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
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)
@jackkoppa
Copy link
Author

jackkoppa commented Oct 2, 2018

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 catch null and undefined).

When you'll be following up the existence check by accessing a property, or checking if a property exists, null and undefined are indeed the only 2 falsy values to throw type errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment