Understanding the difference between null and undefined in TypeScript is one of the simplest ways to prevent hidden bugs, build predictable apps, and write code that other developers can instantly understand.
Both represent “no value,” but they serve different purposes—and TypeScript treats them differently depending on your compiler settings.
Let’s break this down clearly.
undefined means a variable has been declared but hasn’t been assigned a value yet.
It’s the default state of:
Example
let user; console.log(user); // undefined
Use it when a value is not ready yet, or when something is optional.
Examples:
null represents the intentional absence of a value.
This is not “missing by accident”—it’s “I’m telling you this is empty.”
Example
let user = null; console.log(user); // null
Use it when:
🔥 Key Differences Between Null and Undefined
| Feature | undefined | null |
|---|---|---|
| Meaning | Not assigned yet | Empty on purpose |
| Default value? | Yes | No |
| Type | undefined | object (JS quirk) |
| Used for | Optional / uninitialized | Intentional absence |
| Common in | JS runtime behavior | API design & data modeling |
When other developers read your code, they understand why something is empty.
With TypeScript’s strictNullChecks, you prevent values from being accidentally nullable.
Especially when your TypeScript is talking to:
🧪 Practical Code Example: Checking Null and Undefined
function checkValue(value: any): void { if (value === null) { console.log("Value is null: intentionally absent"); } else if (value === undefined) { console.log("Value is undefined: not yet initialized"); } else { console.log("Value exists:", value); } } checkValue(null); // Value is null checkValue(undefined); // Value is undefined checkValue("Jomar"); // Value exists: Jomar
Databases frequently return null, not undefined.
Optional parameters default to undefined.
When strictNullChecks is off, both behave the same and can cause bugs.
When on, TypeScript forces you to:
let user: string | null = null;
This improves reliability dramatically.
"strictNullChecks": true
Predictability > convenience.
Use undefined for optional/uninitialized. Use null for intentional emptiness.
A legacy bug in early JavaScript engines—kept for backward compatibility.
TypeScript’s own docs and team recommend using undefined for missing values, null only when deliberate.
JSON supports null but not undefined.
Absolutely. It forces you to treat nullable values more intentionally, preventing runtime errors.
Ready to make your online presence shine? I'd love to chat about your project and how we can bring your ideas to life.
Free Consultation