Course contentsShow
← TypeScript
Lesson 203 of 1,7965. Type Narrowing FundamentalsFree lesson

Loose Equality == null Pattern

The special case where == null checks for both null and undefined simultaneously in TypeScript.

Loose Equality == null Pattern

What you'll learn: How the == null check provides a concise way to test for both null and undefined at once in TypeScript.

The Double-Purpose Null Check

You've learned that strict equality (===) is usually the right choice in JavaScript and TypeScript. But there's one special exception where loose equality (==) becomes genuinely useful: checking for "nullish" values.

When you write value == null, JavaScript's loose equality rules create a happy accident: this expression returns true if value is either null or undefined, and false for everything else.

Why This Works

In JavaScript's loose equality table, null == undefined evaluates to true, and both only equal themselves and each other. This means:

  • null == null → true
  • undefined == null → true
  • 0 == null → false
  • '' == null → false
  • false == null → false

TypeScript's control flow analysis understands this pattern and narrows accordingly.

The Practical Benefit

Instead of writing:

if (value === null || value === undefined)

You can write:

if (value == null)

Both narrow the type identically, but the second is more concise. This is particularly useful when a value might be legitimately null or undefined, and you want to handle both cases together.

Key Takeaway: The == null pattern is the only widely-accepted use of loose equality in modern TypeScript—it concisely checks for both null and undefined in a way TypeScript's type narrowing fully understands.