TypeScript null and undefined

TypeScript tutorial

🚫 TypeScript null and undefined

In TypeScript null and undefined represent absence of a value, but they are not the same.

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.”

let a: number;
console.log(a); // undefined

Function without return:

function log(): void {}

2️⃣ What is null?

  • null is an intentional empty value.

  • It means “no value on purpose.”

let b: string | null = null;

📌 You explicitly assign null.


3️⃣ Key Difference

Featureundefinednull
MeaningNot assignedIntentionally empty
Default valueYesNo
Assigned byJS engineDeveloper
Common useMissing valueCleared value

4️⃣ strictNullChecks (Very Important ⭐)

When strictNullChecks: true (default in modern TS):

❌ This is not allowed:

let name: string = null;

✅ Correct:

let name: string | null = null;

5️⃣ Union Types with null / undefined

Very common in real projects.

let username: string | undefined;
let email: string | null;

6️⃣ Optional Parameters = undefined

Optional parameters are automatically undefined.

function greet(name?: string) {
console.log(name);
}

Equivalent to:

function greet(name: string | undefined) {}

7️⃣ Nullish Coalescing (??)

Use a default value only when value is null or undefined.

let input: string | null = null;

let result = input ?? “Default”;

null → “Default”
undefined → “Default”
"" (empty string) → NOT replaced


8️⃣ Optional Chaining (?.)

Safely access properties that may be null or undefined.

type User = {
profile?: {
name: string;
};
};
const user: User = {};console.log(user.profile?.name); // undefined (no error)


9️⃣ Checking null & undefined

Use strict checks:

if (value === null) {}
if (value === undefined) {}

Or combined:

if (value == null) {
// checks both null & undefined
}

🔟 Common Mistake ❌

function printLength(str: string) {
console.log(str.length);
}

✔ Safe version:

function printLength(str: string | null) {
if (str !== null) {
console.log(str.length);
}
}

🔑 Summary

ConceptExplanation
undefinedNot assigned
nullIntentionally empty
strictNullChecksEnforces 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

You may also like...