TypeScript null and undefined

🚫 TypeScript null and undefined
Understanding them is crucial—especially when strictNullChecks is enabled (recommended).
1️⃣ What is undefined?
A variable that is declared but not assigned has the value
undefined.It usually means “not initialized yet.”
Function without return:
2️⃣ What is null?
nullis an intentional empty value.It means “no value on purpose.”
📌 You explicitly assign null.
3️⃣ Key Difference
| Feature | undefined | null |
|---|---|---|
| Meaning | Not assigned | Intentionally empty |
| Default value | Yes | No |
| Assigned by | JS engine | Developer |
| Common use | Missing value | Cleared value |
4️⃣ strictNullChecks (Very Important ⭐)
When strictNullChecks: true (default in modern TS):
❌ This is not allowed:
✅ Correct:
5️⃣ Union Types with null / undefined
Very common in real projects.
6️⃣ Optional Parameters = undefined
Optional parameters are automatically undefined.
Equivalent to:
7️⃣ Nullish Coalescing (??)
Use a default value only when value is null or undefined.
✔ null → “Default”
✔ undefined → “Default”
❌ "" (empty string) → NOT replaced
8️⃣ Optional Chaining (?.)
Safely access properties that may be null or undefined.
9️⃣ Checking null & undefined
Use strict checks:
Or combined:
🔟 Common Mistake ❌
✔ Safe version:
🔑 Summary
| Concept | Explanation |
|---|---|
undefined | Not assigned |
null | Intentionally empty |
strictNullChecks | Enforces safety |
| Union types | `string |
?? | Default for null/undefined |
?. | Safe property access |
⭐ Best Practices
✔ Always enable strictNullChecks
✔ Use union types explicitly
✔ Prefer ?? over ||
✔ Use optional chaining to avoid crashes
