null vs undefined in JavaScript
Two distinct primitive types that both represent absence of value, but with different semantics and use cases.
| Feature | null | undefined |
|---|---|---|
| Type | object (historical bug in JS) | undefined |
| Set by | Developer explicitly | JavaScript engine (usually) |
| Meaning | Intentional absence of value | Variable declared but not assigned |
| typeof null | "object" | |
| JSON support | JSON.stringify(null) = "null" | Omitted from JSON.stringify |
| Default value | Not a default for anything | Default for unset variables, missing params, missing properties |
Verdict
Use null when you want to explicitly indicate no value. Let undefined be JavaScript's default for uninitialized values. Check both with == null or the ?? operator.
Code Example
Related Tutorials
Related Glossary Terms
In JavaScript, every value is either truthy or falsy when evaluated in a boolean context. Falsy values are: false, 0, '', null, undefined, NaN, and 0n. Everything else is truthy, including empty arrays and objects.
Nullish CoalescingThe ?? operator that returns the right-hand operand when the left-hand operand is null or undefined. Unlike ||, it does not treat 0, '', or false as nullish, making it safer for default values.
Optional ChainingThe ?. operator that safely accesses deeply nested object properties without throwing if an intermediate value is null or undefined. Returns undefined instead of throwing a TypeError.