In TypeScript, both undefined and null represent the absence of a value, but they serve different purposes and behave differently in code.
Key Differences
-
Definition:
-
undefined: Automatically assigned to variables that have been declared but not initialized. -
null: Must be explicitly assigned to indicate a variable intentionally has no value.
-
-
Type System:
- By default, variables can be
undefinedbut notnullunless you adjust your TypeScript configuration (strictNullChecks).
- By default, variables can be
Examples
let a: number;
console.log(a); // undefined
let b: number | null = null;
console.log(b); // null
- In the first example,
ais declared but not initialized, so it isundefined. - In the second example,
bis explicitly set tonull.
Practical Use Cases
- Use
undefinedto check if a value was ever assigned. - Use
nullto deliberately clear a value.
let list: number[] | null = [1, 2, 3];
// Later
list = null; // The list is deliberately cleared
Summary:
-
undefinedmeans a variable has no assigned value. -
nullis an intentional assignment of "no value."
Top comments (0)