null vs undefined in TypeScript
10 null and undefined are not the same thing
fairDeclare one variable holding null and one holding undefined. Show how they differ, and show the operator that treats them as the same when you want that.
Stuck? Three hints, smallest first
- 1.
undefinedmeans "nobody set this".nullmeans "somebody set this to nothing". - 2.
==treats them as equal;===does not. This is the one case where==is genuinely useful. - 3.
??supplies a fallback for null or undefined only, and leaves0and''alone.||replaces those too.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
const isNull: null = null;
const isUndefined: undefined = undefined;
console.log('typeof null:', typeof isNull); // "object", a famous bug
console.log('typeof undefined:', typeof isUndefined); // "undefined"
console.log('loose equal:', isNull == isUndefined); // true
console.log('strict equal:', isNull === isUndefined); // false
// Where the difference bites: a fallback.
function seatsLeft(value: number | null | undefined): number {
return value ?? 14; // only null and undefined are replaced
}
function seatsLeftWrong(value: number | null | undefined): number {
return value || 14; // 0 is falsy, so a full bus reads as empty
}
console.log('?? with 0 :', seatsLeft(0));
console.log('|| with 0 :', seatsLeftWrong(0));
test('typeof null is object', typeof isNull, 'object');
test('== sees them as equal', isNull == isUndefined, true);
test('=== does not', isNull === isUndefined, false);
test('?? keeps a real zero', seatsLeft(0), 0);
test('|| loses a real zero', seatsLeftWrong(0), 14);
test('?? still fills in for null', seatsLeft(null), 14);
Output
The 0 case is the reason this matters. A bus with 0 seats left is a real answer, and value || 14 silently turns it into a bus with fourteen free seats. Use ?? whenever the fallback is for "missing", and keep || for "missing or empty or zero", which is rarer than people think.