3️⃣ 🧪 TypeScript Core & Special Types
Estimated reading: 4 minutes 32 views

🌑 TypeScript — Null vs. Undefined: Understanding the Differences

🧲 Introduction – What Are null and undefined in TypeScript?

In TypeScript, both null and undefined represent absence of value, but they serve different semantic purposes. Confusing them can lead to subtle bugs, especially when strict null checks are enabled.

🎯 In this guide, you’ll learn:

  • The difference between null and undefined
  • How TypeScript treats them with and without strict mode
  • Best practices for handling nullability
  • Real-world examples and common pitfalls

🔍 What Is undefined in TypeScript?

undefined means a variable has been declared but has not been assigned a value yet.

✅ Example:

let user;
console.log(user); // undefined

🔎 Explanation:

  • user is declared but not initialized, so its value is undefined by default.
  • This is automatically assigned by JavaScript/TypeScript.

🕳️ What Is null in TypeScript?

null is an explicit assignment indicating that a variable is intentionally empty or has “no value.”

✅ Example:

let response: string | null = null;

🔎 Explanation:

  • You deliberately assign null to show that the value is empty on purpose.
  • TypeScript will not allow null unless it’s included in the type (string | null).

🔧 TypeScript Configuration – strictNullChecks

The behavior of null and undefined is controlled by the strictNullChecks flag in tsconfig.json.

🔹 Without strictNullChecks (default in older TS versions):

let name: string = null;       // ✅ Allowed
let age: number = undefined;   // ✅ Allowed

🔹 With strictNullChecks: true (recommended):

let name: string = null;       // ❌ Error
let age: number = undefined;   // ❌ Error

✅ Solution: Use union types.

let name: string | null = null;
let age: number | undefined = undefined;

🔁 Practical Differences

Featurenullundefined
Default value for vars❌ No✅ Yes
Typenullundefined
IntentExplicit absence of valueImplicit uninitialized state
Strict checkRequires `null` in type
JSON.stringifySerializedIgnored
typeof result"object""undefined"

💡 Use Cases

✅ When to Use null:

  • API response is intentionally empty
  • You want to explicitly reset a value
  • Clear intention to signal “no value”
let selectedUser: string | null = null;

✅ When to Use undefined:

  • Variable declared but not initialized
  • Optional function parameters
  • Missing object properties
function greet(name?: string) {
  console.log(`Hello, ${name ?? "Guest"}`);
}

🧪 Type Narrowing with null and undefined

✅ Using optional chaining and nullish coalescing:

let user = {
  name: "Alice",
  address: null
};

console.log(user.address?.city); // undefined
console.log(user.address ?? "No address"); // "No address"

⚠️ Common Mistakes & How to Avoid Them

❌ Mistake✅ Solution
Assigning null to non-nullable variableUse union types (`string
Using equality instead of strict equalityUse === or !== to distinguish values accurately
Forgetting optional chainingUse ?. to prevent runtime errors on possibly null values
Treating null and undefined as sameKnow their behavioral differences

🔒 Best Practices

  • ✅ Enable strictNullChecks in your tsconfig.json
  • ✅ Use union types for nullable or optional values
  • ✅ Use undefined for optional params and default states
  • ✅ Use null for intentional resets and known emptiness
  • 🔄 Use nullish coalescing (??) to handle fallback values safely

📌 Summary – Recap & Next Steps

Understanding the differences between null and undefined helps you write robust and bug-free TypeScript code. Use undefined when values are not yet assigned, and null when they are intentionally empty.

🔍 Key Takeaways:

  • undefined = not assigned; null = deliberately empty
  • Enable strictNullChecks for better type safety
  • Use ?., ??, and type unions to handle nullable logic
  • Avoid assigning null or undefined without explicitly stating it in types

⚙️ Real-world relevance: Crucial in handling API responses, user inputs, form values, and conditional rendering in both frontend and backend TypeScript apps.


❓ FAQs – Null vs Undefined in TypeScript

❓ Can a variable be both null and undefined?
✅ Yes, but only if typed as: let data: string | null | undefined.

❓ Should I use null or undefined by default?
📌 Use undefined for optional or uninitialized values, null for intentional absence.

❓ Is null == undefined true in JavaScript/TypeScript?
✅ Yes. But null === undefined is ❌ false. Always use strict equality checks (===).

❓ Are null and undefined included in JSON?
📌 null is included in JSON, but undefined properties are omitted.

❓ Can I use ?? to check for both null and undefined?
✅ Yes. ?? (nullish coalescing) treats both null and undefined as empty values.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

TypeScript — Null / null vs. undefined

Or Copy Link

CONTENTS
Scroll to Top