Null and Undefined
In this page:
Undefined Type
A variable naturally holds the value undefined when no value has ever been assigned to it, or when it's explicitly set to undefined. It's JavaScript's, and by extension TypeScript's, default "nothing here yet" state.
Example: Undefined Type
let username: string | undefined;
console.log(username); // undefined, no value assigned yet
Null Type
The null value represents an intentionally empty value, deliberately set by code to mean "there is no value" rather than "no value was ever assigned." A variable typed strictly as null can only ever hold that one value.
Example: Null Type
let selected: null = null;
console.log(selected);
Union with Null
A union type can combine a normal type with null, written as Type | null, to signal that a value might legitimately be missing. This forces anyone using that value to handle the missing case explicitly rather than assuming it's always present.
Example: Union with Null
let city: string | null = null;
city = "Chennai";
console.log(city);
Checking Null and Undefined
Before using a value that might be null or undefined, checking for its presence lets TypeScript narrow the type for the rest of that code block, removing null or undefined from the possibilities. This is how TypeScript's control-flow analysis eliminates the need for manual type assertions after a guard.
Example: Checking Null and Undefined
let city: string | null = null;
if (city !== null) {
console.log(city.toUpperCase());
} else {
console.log("No city set");
}
Nullish Coalescing
The nullish coalescing operator, written as ??, provides a fallback value specifically when the left-hand side is null or undefined. Unlike the older || operator, it correctly leaves valid falsy values like 0 or an empty string untouched instead of replacing them.
Example: Nullish Coalescing
let count: number | null = null;
let total = count ?? 0;
console.log(total); // 0, since count is null
let zero: number | null = 0;
console.log(zero ?? 99); // 0, since 0 is not null/undefined
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: