undefined vs null — Subtle Differences
TL;DR
undefined means 'not yet assigned' (declared but empty); null means 'intentionally absent' — they're different values but both falsy, and typeof null === 'object' is a famous JS bug.
Explanation
undefined: default value of unassigned variables, missing object properties, missing function parameters, void function return. null: explicit absence, intentional empty value. Key differences: typeof undefined === 'undefined', typeof null === 'object' (JS bug from 1995, can't fix). null == undefined (true), null === undefined (false). JSON.stringify converts undefined to nothing, null to 'null'. Optional chaining: obj?.prop returns undefined for missing, not null. Best practice: use null for intentional absence, never assign undefined explicitly.
Common Misconception
✗ null and undefined are interchangeable — they're different values. null == undefined (loose) but null !== undefined (strict). JSON treats them differently.
Why It Matters
Confusing null and undefined causes subtle bugs in comparisons and JSON serialisation — especially in API contracts where null means 'explicitly empty' vs missing field.
Common Mistakes
- Assigning undefined explicitly — use null for intentional absence.
- Using == instead of === which treats null and undefined as equal.
- Forgetting that JSON.stringify drops undefined values but preserves null.
Code Examples
✗ Vulnerable
// Both are falsy but behave differently:
const a = null;
const b = undefined;
console.log(a == b); // true
console.log(a === b); // false
console.log(JSON.stringify({a, b})); // {"a":null} (b dropped!)
✓ Fixed
// Explicit null for intentional absence:
const user = fetchUser() ?? null; // null if not found
// Strict null checks:
if (value === null) { /* intentionally empty */ }
if (value === undefined) { /* not yet set */ }
if (value == null) { /* either null or undefined */ }
// TypeScript helps:
function getUser(id: string): User | null { }
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
22 Mar 2026
Edited
5 Apr 2026
Views
26
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 6
Unknown AI 4
Google 4
Perplexity 4
ChatGPT 2
Majestic 1
Meta AI 1
Ahrefs 1
Also referenced
How they use it
crawler 20
pre-tracking 3
Related categories
⚡
DEV INTEL
Tools & Severity
🟢 Low
⚙ Fix effort: Low
⚡ Quick Fix
Use null for intentional absence, never assign undefined explicitly. Use === for comparisons. Use ?? (nullish coalescing) to handle both. Use TypeScript strict null checks.
📦 Applies To
javascript ES5
web
cli
🔗 Prerequisites
🔍 Detection Hints
=== undefined|== null
Auto-detectable:
✓ Yes
eslint
typescript
⚠ Related Problems
🤖 AI Agent
Confidence: Medium
False Positives: High
✗ Manual fix
Fix: Low
Context: Line