How can I tell the difference between `undefined` and `null` in JavaScript?
Quick answer
undefined and null are distinct JavaScript primitive values. undefined commonly appears for an uninitialized variable or when a lookup finds no result; null is often used intentionally to represent absence. Neither is automatically an error—the right choice depends on what your code expects. Use === when the distinction matters: null === undefined is false. [S1] [S2]
The question, the details, the next step.
A practical checklist
Decide whether the code needs to distinguish the two values.
Use
=== undefinedand=== nullfor separate checks.Use a combined loose-equality check only when treating both values alike is intentional.
Check that your handling matches what the program expects.
A few more useful answers
Does `null === undefined` return `true?
No. Strict equality does not convert values, so null === undefined is false. [S2]
Does `null == undefined` return `true`?
Yes. Loose equality has special handling for this pair. It is suitable only when you intentionally want one check to match both. [S2]
Is either value always an error?
No. Whether undefined or null is appropriate depends on what the program expects. [S1]
Sources
References used for this guide.
- [S1] JavaScript data types and data structures — MDN developer.mozilla.org · Checked
- [S2] Equality comparisons and sameness — MDN developer.mozilla.org · Checked
