Sub topic 1
null and undefined: two ways to say "no value"
Prerequisites
This chapter assumes you can read basic TypeScript: primitive types, interfaces, union types such as string | number, and type annotations on variables and functions. You should also know that JavaScript has the values null and undefined, even if you have never thought hard about the difference. You need a tsconfig.json only to follow the last section. Every example runs as plain TypeScript or JavaScript.
Why two values exist
Most languages have one way to say "nothing here". JavaScript has two, and TypeScript models both. The rest of this tutorial is about stopping either one from reaching code that does not expect it. This chapter covers what the two values mean at runtime and where each comes from.
undefinedmeans "no value has been provided". The language itself produces it.nullmeans "there is deliberately no value". Programmers, libraries, and data formats produce it.
The distinction is a convention, and nothing enforces it. In practice, though, the language creates undefined in many places and null in only a few.
Where undefined comes from
You rarely write undefined yourself. The runtime hands it to you in these situations:
let declared: string | undefined; // declared, never assigned
console.log(declared); // undefined
const settings: { theme?: string } = {}; // property that does not exist
console.log(settings.theme); // undefined
function describe(label?: string) { // argument that was not passed
return label;
}
console.log(describe()); // undefined
function noReturn() {} // function with no return statement
console.log(noReturn()); // undefined
const items = [1, 2, 3];
console.log(items[10]); // undefined (TypeScript still types this as number)The last line is a known gap in the type system. Indexing past the end of an array gives undefined at runtime, but the type is number. A later chapter covers the noUncheckedIndexedAccess option, which closes that gap.
Where null comes from
null appears only when something puts it there. The most common sources are:
- Your own code, when you want to say "this is empty on purpose".
- JSON, which has
nullbut noundefined. - Browser APIs such as
document.querySelector, which returnnullwhen nothing matches. - Database drivers and HTTP APIs that map a missing column or field to
null.
const parsed = JSON.parse('{"title": "Draft", "publishedAt": null}');
console.log(parsed.publishedAt); // null
console.log(parsed.author); // undefined (the key is absent)Here the same object produces both values. publishedAt is present and explicitly empty. author is absent. Code that reads data from outside your program will often meet both.
How the two behave differently
They are different values of different types, but they overlap in several ways. This table lists the behaviors you will meet most often.
| Operation | `undefined` | `null` |
|---|---|---|
| `typeof` | `"undefined"` | `"object"` (a historical bug) |
| `=== null` | `false` | `true` |
| `== null` | `true` | `true` |
| `Number(x)` | `NaN` | `0` |
| `String(x)` | `"undefined"` | `"null"` |
| Triggers a default parameter | Yes | No |
| `JSON.stringify` in an object | Property is omitted | Written as `null` |
| Truthiness | falsy | falsy |
The code below shows the equality rules. The variables are typed unknown so the compiler lets you compare any pair.
const a: unknown = null;
const b: unknown = undefined;
console.log(a === b); // false: different types
console.log(a == b); // true: loose equality treats them as equal
console.log(a == 0); // false
console.log(a == ""); // false
console.log(typeof a); // "object"
console.log(typeof b); // "undefined"Loose equality (==) has a single special case where null and undefined equal each other and nothing else. That is why x == null is a compact test for "null or undefined". It is also one of the few places where TypeScript style guides allow ==.
The typeof null result is a bug from the first version of JavaScript that cannot be fixed without breaking the web. Never use typeof x === "object" to mean "x is a real object" without also excluding null.
Default values react only to undefined
A default parameter or destructuring default applies when the incoming value is undefined. It does not apply to null.
function greet(name: string | null = "guest"): string {
return `Hello, ${name ?? "nobody"}`;
}
console.log(greet()); // Hello, guest
console.log(greet(undefined)); // Hello, guest
console.log(greet(null)); // Hello, nobodyThis surprises many people. Passing null is read as "I meant to pass nothing", so the default is skipped. The same rule holds for destructuring:
const { retries = 3 } = { retries: null as number | null };
console.log(retries); // null, not 3The ?? operator in the first example is covered in its own chapter. For now, note that it treats the two values alike.
Missing versus present-but-undefined
A property can be absent, or it can exist with the value undefined. Property access cannot tell them apart. The in operator and Object.keys can.
const absent: { x?: number } = {};
const explicit: { x?: number } = { x: undefined };
console.log(absent.x); // undefined
console.log(explicit.x); // undefined
console.log("x" in absent); // false
console.log("x" in explicit); // true
console.log(Object.keys(explicit)); // ["x"]
console.log(JSON.stringify(explicit)); // {}JSON drops undefined properties, so a round trip through JSON.stringify and JSON.parse turns "explicitly undefined" into "absent". In arrays, JSON.stringify([undefined]) gives [null], because an array slot cannot be omitted. The exactOptionalPropertyTypes option, covered in a later chapter, lets TypeScript model this difference.
One more edge: undeclared variables
undefined is a value. An undeclared variable is a different thing, and reading it throws an error.
declare const maybeGlobal: unknown;
console.log(typeof maybeGlobal); // safe even if the variable does not exist at runtime
// console.log(maybeGlobal); // would throw ReferenceError if it does not existtypeof is the only operator that does not throw on a name that was never declared. Feature-detection code relies on this. It is rare in application TypeScript, and it matters mainly when you target several environments.
How TypeScript models them
TypeScript has a type named null and a type named undefined. Each has exactly one value.
let onlyNull: null = null;
let onlyUndefined: undefined = undefined;
// A type that admits either one, or a real value, is a union.
let maybeCount: number | null | undefined = 5;
maybeCount = null;
maybeCount = undefined;A third related type is void. It describes the return type of a function whose result you are not meant to use. A function declared (): void may return undefined, but void and undefined are not interchangeable in every position. Use void for return types and undefined for values.
What these types mean depends on one compiler option, strictNullChecks. The next chapter covers it in full. The short version:
- With
strictNullChecksoff,nullandundefinedare assignable to every type. A variable typedstringcan holdnull, and the compiler will not warn you. This is how TypeScript behaved by default for years. - With
strictNullCheckson,nullandundefinedare assignable only to their own types, to unions that include them, and tounknownandany. Astringis always a string.
Picking a convention
Because the language gives you both values, a codebase should decide how to use them. These rules work well:
- Treat
undefinedas "not provided" or "not set". This matches how optional properties, optional parameters, and missing array items behave. - Treat
nullas "known to be empty", for example a record with no end date. - Do not use both for the same idea in the same data structure. A field that is sometimes
nulland sometimesundefinedforces every reader to check for both. - At boundaries where data enters your program (JSON, databases, DOM), convert to your convention once, and keep the inside of the program consistent.
Some teams use only undefined and convert null at the boundary. Others use null for stored data and undefined for optional arguments. Either works. Mixing them without a rule is the real problem.
The diagram summarizes the flow described above.
Turning on the check
You enable the strict behavior in tsconfig.json:
{
"compilerOptions": {
"strict": true
}
}Setting strict to true turns on strictNullChecks together with the other strict-family options. You can also set "strictNullChecks": true alone if you want only this one. Try it on an existing file and read the errors. Each one marks a place where a value that might be missing was treated as always present.
Common mistakes
- Using
typeof x === "object"as an object check. It is also true fornull. - Expecting
nullto trigger a default. Onlyundefineddoes. - Testing with
if (x)when 0,"", orfalseare valid values. Truthiness also rejects those. Compare withnullorundefineddirectly. - Assuming
JSON.stringifykeepsundefined. Object properties are dropped and array items becomenull. - Trusting
JSON.parse. It returnsany, so the compiler cannot tell you which fields may benullor missing.
Exercise
What does each line print? (1) const o: { n?: number } = { n: undefined }; console.log("n" in o); (2) function f(x = 10) { return x; } console.log(f(null as any)); (3) console.log(JSON.stringify({ a: undefined, b: null }));
Show answer
(1) true, because the property exists even though its value is undefined. (2) null, because default parameters apply only to undefined and the explicit null is kept. (3) {"b":null}, because JSON.stringify omits properties whose value is undefined but writes null as null.
Exercise
A function receives data from JSON.parse and tests if (typeof value === "object") { value.id; }. Explain what can go wrong and give a safer condition.
Show answer
typeof null is "object", so a null value passes the check and value.id throws a TypeError at runtime. A safer condition is value !== null && typeof value === "object", or value != null && typeof value === "object" to also exclude undefined.