Difference Between Null and Undefined in JavaScript
In JavaScript, both null and undefined
represent the absence of a value, but they serve distinct purposes in
code execution. While undefined is the default runtime
value indicating that a variable has been declared but not yet assigned,
null is an explicit assignment used by developers to
represent intentional emptiness. This guide covers their definitions,
type representations, behavior in equality operations, and practical
differences.
1. What is undefined?
undefined means a variable has been declared, but no
value has been assigned to it. It is JavaScript’s default value for
uninitialized states.
You encounter undefined when: * A variable is declared
using let or var without an initial value. * A
function does not explicitly return a value. * You access an object
property or array index that does not exist. * Function parameters are
omitted during a function call.
let a;
console.log(a); // undefined
function test() {}
console.log(test()); // undefined
const obj = {};
console.log(obj.fakeProperty); // undefined2. What is null?
null is an intentional assignment. It represents the
deliberate absence of any object value or an empty state. JavaScript
never sets a value to null automatically; it must be
assigned programmatically.
let user = null; // Explicitly set to represent "no user"3. Type Differences
(typeof)
The typeof operator reveals a fundamental difference
between the two primitives:
typeof undefinedreturns"undefined".typeof nullreturns"object".
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"Note: typeof null === "object" is a legacy bug in
JavaScript that cannot be fixed without breaking existing web
applications.
4. Equality Comparisons
(== vs ===)
When comparing null and undefined, the
result depends on whether you use loose or strict equality:
- Loose Equality (
==): Returnstruebecause both are falsy values representing emptiness. - Strict Equality (
===): Returnsfalsebecause they are different data types.
console.log(null == undefined); // true
console.log(null === undefined); // false5. Arithmetic Operations
When converted to numbers, null and
undefined behave differently:
nullconverts to0.undefinedconverts toNaN(Not a Number).
console.log(null + 5); // 5 (0 + 5)
console.log(undefined + 5); // NaN (NaN + 5)Summary of Differences
| Feature | undefined |
null |
|---|---|---|
| Meaning | Value does not exist / unassigned | Value is intentionally empty |
| Set by | JavaScript engine (default) | Programmer (explicit) |
| Type | "undefined" |
"object" |
| Numeric Conversion | NaN |
0 |
| JSON Serialization | Keys with undefined are
omitted |
Keys with null are
preserved |