JavaScript Null vs Undefined
Difference Between null & undefined
| Value | Meaning |
|---|---|
| null | A value has been deliberately set to "no value". |
| undefined | A value is expected. No value has been assigned yet. |
Null and undefined have different values.
| Null | Undefined |
|---|---|
| Intentional value absence | No value yet assigned |
| Type is "null" | Type is "undefined" |
typeof is "object" |
typeof is "undefined" |
Examples
let x = null;
let a = x; // a = null
Try it Yourself »
let x;
let a = x; // a = undefined
Try it Yourself »
Comparing Null and Undefined
Loose equality treats null and undefined as equal.
Strict equality does not.
Comparing Type
undefined and null have different typeof values.
| Expression | Result |
|---|---|
typeof undefined |
"undefined" |
typeof null |
"object" |
Nullish Coalescing
The nullish coalescing operator (??) treats both null and undefined as missing values.
Examples
let person = undefined;
let name = (person ?? "unknown");
Try it Yourself »
let person = null;
let name = (person ?? "unknown");
Try it Yourself »
Summary
| Question | Answer null | Answer undefined |
|---|---|---|
| Primitive Type | null | undefined |
| Possible Values | Only 1 (null) | Only 1 (undefined) |
| False | Yes | Yes |
| Object | No | No |
| typeof | "object" | "undefined" |