Lessons · TypeScript · never set, or set to nothing
Two kinds of nothing
undefined is the absence nobody chose: a variable never assigned, a missing property. null is an absence someone set on purpose.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
APIs return null to mean 'known to be empty'; JavaScript produces undefined to mean 'never there'. Keeping them apart makes intent readable, and ?? treats both as missing when that is what you want.
How to think about it
Let undefined mean 'not provided' and use null when you deliberately clear something. Check for both at once with == null or ??; check for one specifically with ===.
Worked example
let a;Declared, never given a value.
console.log(a);undefined.
let b = null;An absence someone chose.
console.log(b, typeof a, typeof b);null undefined object.
console.log(a ?? "none", b ?? "none");none none: ?? treats both as missing.
Your turn
A display name with a fallback.
const name = user.nick "anonymous";
Solve one with the tests running
The trap
JSON has null but no undefined. A property set to undefined vanishes from JSON.stringify; null survives the round trip.