Javascript Check Null or Undefined
In JavaScript, a value could be nullish or not nullish, and a value could be falsy or truthy.
Nullish values are a proper subset of falsy values:
╭─ nullish ──────╮ ╭─ not nullish ─────────────────────────────────╮
┌───────────┬──────┬───────┬───┬────┬─────┬──────┬───┬─────────┬─────┐
│ undefined │ null │ false │ 0 │ "" │ ... │ true │ 1 │ "hello" │ ... │
└───────────┴──────┴───────┴───┴────┴─────┴──────┴───┴─────────┴─────┘
╰─ falsy ───────────────────────────────╯ ╰─ truthy ───────────────╯
Check if value is nullish (undefined or null)
Use one of the following depending on your coding style:
if (value == null) { /* value is nullish */ }
if (value === undefined || value === null) { /* value is nullish */ }
if (value == undefined) { /* value is nullish */ }
if ((value ?? null) === null) { /* value is nullish */ }Notes:
- The == operator works because it has a special case for null vs undefined comparison
- The === operator is more readable (opinion based), eqeqeq friendly and allows checking for undefined and null separately
- The first and third examples work identically, however the third one is rarely seen in production code
- The fourth example uses nullish coalescing operator to change nullish values to
nullfor straight forward comparison
Check if value is not nullish
if (value != null) { /* value is not nullish, although it could be falsy */ }
if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ }
if (value != undefined) { /* value is not nullish, although it could be falsy */ }
if ((value ?? null) !== null) { /* value is not nullish, although it could be falsy */ }Check if value is falsy
Use the ! operator:
if (!value) { /* value is falsy */ }Check if value is truthy
if (value) { /* value is truthy */ }