TypeScript null and undefined

TypeScript undefined

In TypeScript, if a variable is declared without a value, its type is implicitly undefined unless otherwise specified. For example,

let userName: string | undefined;
console.log(userName); // undefined

You can also assign undefined explicitly:

let userName: string | undefined = "Felix";
userName = undefined;
console.log(userName); // undefined

Note: To allow undefined, the variable type must explicitly include it (string | undefined), otherwise you'll get a compile-time error.


TypeScript null

null in TypeScript represents an intentional absence of any object value:

let num: number | null = null;

Note: TypeScript distinguishes between null and undefined, and with --strictNullChecks, you must explicitly include null or undefined in the type.


False Values

Both null and undefined are falsy in TypeScript (just like JavaScript):

if (null || undefined) {
  console.log("true");
} else {
  console.log("false");
}
// Output: false

They also evaluate to false with Boolean():

console.log(Boolean(undefined)); // false
console.log(Boolean(null)); // false

TypeScript typeof: null and undefined

const a = null;
console.log(typeof a); // "object"

let b: undefined;
console.log(typeof b); // "undefined"

Same behavior as JavaScript: typeof null === "object".


TypeScript Default Values: null vs undefined

When passing undefined to a function parameter with a default, the default is used:

function greet(x: number = 10) {
  console.log(x);
}

greet(undefined); // 10

When passing null, it overrides the default:

greet(null as any); // null (TypeScript will warn unless casted)

However, when you pass null to a default parameter function, the function takes the null as a value. For example,

function test(x = 1) {
  console.log(x);
}

// passing undefined
// takes null
test(null); // null

Comparing null and undefined

Using == :

console.log(null == undefined); // true

Using === :

console.log(null === undefined); // false

Your path to become a builder.

Builders don’t just know how to code, they create solutions that matter. Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community