DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Undefined vs Null in TypeScript: What’s the Difference?

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 undefined but not null unless you adjust your TypeScript configuration (strictNullChecks).

Examples

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

let b: number | null = null;
console.log(b); // null
Enter fullscreen mode Exit fullscreen mode
  • In the first example, a is declared but not initialized, so it is undefined.
  • In the second example, b is explicitly set to null.

Practical Use Cases

  • Use undefined to check if a value was ever assigned.
  • Use null to deliberately clear a value.
let list: number[] | null = [1, 2, 3];
// Later
list = null; // The list is deliberately cleared
Enter fullscreen mode Exit fullscreen mode

Summary:

  • undefined means a variable has no assigned value.
  • null is an intentional assignment of "no value."

Top comments (0)