Skip to content

Instantly share code, notes, and snippets.

@the-vishal-kumar
Last active September 1, 2021 04:21
Show Gist options
  • Save the-vishal-kumar/dad8faf34c103e722ad74484ae8ef0fc to your computer and use it in GitHub Desktop.
Save the-vishal-kumar/dad8faf34c103e722ad74484ae8ef0fc to your computer and use it in GitHub Desktop.
How to check for null in JavaScript
  • Checking for null is a common task that every JavaScript developer has to perform at some point or another
  • The typeof keyword returns "object" for null, so that means a little bit more effort is required
  • Comparisons can be made:
    • null === null to check strictly for null
    • null == undefined to check loosely for either null or undefined
  • The value null is falsy, but empty objects are truthy, so typeof maybeNull === "object" && !maybeNull is an easy way to check that a value is not null
  • Finally, to check if a value has been declared and assigned a value that is neither null nor undefined, use typeof
    • typeof maybeUndeclared !== "undefined" && (typeof maybeUndeclared !== "object" || !maybeUndeclared)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment