Code Writing
Null vs Undefined
Two ways to say "nothing", but with very different meanings.
Know the difference.
Know the difference.
The Golden Rule
A mental model to keep them straight.
Undefined
"No value provided"
The variable exists, but nothing has been put into it yet. It's the default state of things.
Null
"Empty value"
Intentionally set to be empty. We checked, and the answer is explicitly "nothing".
Undefined: No Value Provided
Use this when a value is optional or hasn't been initialized.
Optional Parameters
When you don"t pass an argument, JavaScript automatically assigns it "undefined". It simply means "missing".
Null: Intentional Empty Value
Use this when you want to explicitly say "this is empty".
Resetting State
We use "null" to reset the selection. We aren"t saying the selection is "missing" (undefined), we are saying it is "empty" (null).
Explicit vs Implicit
Sometimes "optional" is too ambiguous. Use null to force a decision.
Optional (Ambiguous)
Ambiguity is dangerous here. If "undefined" means "ignore", we have no way to unassign the user without a separate function.
Nullable (Explicit)
We use "undefined" for "ignore" (no change) and "null" for "remove" (clear value). Distinct and critical.
Quick Reference
❓
Variable declared but not assigned → It is undefined
📥
Function argument not passed → It is undefined
🚫
Resetting a form field → Set it to null
🔍
API returns "not found" → Ideally returns null