Skip to content

Instantly share code, notes, and snippets.

@eddieantonio
Created April 24, 2020 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddieantonio/2664cc5902516035949b732bbe19ac2b to your computer and use it in GitHub Desktop.
Save eddieantonio/2664cc5902516035949b732bbe19ac2b to your computer and use it in GitHub Desktop.
Checking for `null` or `undefined` in JavaScript

Checking for null or undefined in JavaScript

Say I want to check if a value v is either null or undefined in JavaScript. I might use this conditional:

if (!v) { ... } // 🙅‍♀️ wrong!

Because of JavaScript's weak typing, this conditional will catch way more than just null and undefined.

Instead, use this:

if (v == undefined) { ... } // ✅ right!

This uses the weakly-typed == to our advantage. According to the ECMAScript spec, x == y is true when x is null and y is undefined; trivially, it's also true when x and y are the exact same value (e.g.,. both x and y are undefined). This behaviour is explicit in the definition of ==, so this is one of the only times I prefer to use == over the far stricter (and safer) === comparison.

Truth table

I've listed here a bunch of different values of v and the results of !v and v == undefined:

v desired !v v == undefined
undefined true true true
null true true true
0 false true false
false false true false
'' false true false
NaN false true false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment