Is there a way to check for both `null` and `undefined`?
Yes. In JavaScript (and TypeScript), a common trick is to use the loose equality check (==
) against null
, which covers both null
and undefined
—because x == null
is true if x
is either null
or undefined
. Alternatively, you can explicitly check x === null || x === undefined
.
1. The == null
Trick
if (x == null) { // This means x is either null or undefined console.log("x is null or undefined"); }
- Using
==
(instead of===
) is typically discouraged because it can be confusing, butx == null
is one of the few recommended exceptions, as it precisely checks for bothnull
andundefined
.
Example
let a = null; let b; console.log(a == null); // true, because a is null console.log(b == null); // true, because b is undefined
2. Explicit Check for null
or undefined
You can also do this in a more explicit way:
if (x === null || x === undefined) { console.log("x is null or undefined"); }
- This uses strict equality and might be clearer in some codebases where loose equality (
==
) is disallowed by style rules. - Functionally, it’s the same as
x == null
but more verbose.
3. TypeScript Implications
If you’re in TypeScript with "strictNullChecks"
enabled, it’s common to see code that checks for null
or undefined
before proceeding. For instance:
function processValue(x: string | null | undefined) { // If x isn't null or undefined, we can use it as string if (x != null) { console.log(x.toUpperCase()); } }
- The
!= null
check (loose) is often used in TypeScript to guard against both possibilities.
4. Summary
x == null
(loose equality) is a concise approach to check ifx
is eithernull
orundefined
.x === null || x === undefined
is a stricter, more explicit approach.- In TypeScript, both patterns are valid and commonly used, especially with
strictNullChecks
.
Bonus: If you want to strengthen your JavaScript fundamentals—which TypeScript builds upon—consider the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers key JS concepts like prototypes, closures, and async patterns, which help you write more robust and clear TypeScript code.