Null vs Undefined in JavaScript – Difference and Use Cases
In JavaScript, null
and undefined
are two distinct values that represent the absence of a meaningful value. Understanding their differences, usage, and behavior is crucial for writing clean and bug-free code.
null
- Represents an intentional absence of any object value.
- Explicitly assigned to indicate “no value” or “empty.”
- Type:
"object"
(this is a historical quirk in JavaScript).
let user = null;
console.log(user); // null
console.log(typeof user); // "object"
undefined
- Indicates a variable has been declared but not assigned a value, or a value is not available.
- Automatically assigned by JavaScript to uninitialized variables or missing object properties.
- Type:
"undefined"
let x;
console.log(x); // undefined
console.log(typeof x); // "undefined"
Key Differences
Aspect | null | undefined |
---|---|---|
Meaning | Explicitly “no value” or empty | Value not assigned or not defined |
Type | "object" | "undefined" |
Assignment | Must be assigned manually: let x = null; | Automatically assigned to uninitialized variables |
Use Case | Intentional absence, clearing variables | Uninitialized state, missing return value, missing property |
Default Value | Not automatic, must be set | Default for uninitialized variables or arguments |
Loose Equality (== ) | null == undefined → true | undefined == null → true |
Strict Equality (=== ) | null === undefined → false | undefined === null → false |
Examples
null Examples
// Explicitly set to indicate "no value"
let user = null;
console.log(user); // null
// Common in objects or APIs
const obj = { name: "Alice", age: null };
console.log(obj.age); // null
undefined Examples
// Variable declared but not assigned
let x;
console.log(x); // undefined
// Missing object property
const obj = { name: "Alice" };
console.log(obj.age); // undefined
// Function with no return
function doNothing() {}
console.log(doNothing()); // undefined
// Missing function argument
function greet(name) {
console.log(name); // undefined if no argument passed
}
greet(); // undefined
Equality Comparison
Loose Equality (==
): null
and undefined
are considered equal:
console.log(null == undefined); // true
Strict Equality (===
): They are not equal due to different types:
console.log(null === undefined); // false
Comparison with other values:
console.log(null > 0); // false
console.log(null == 0); // false
console.log(undefined > 0); // false
console.log(undefined == 0); // false
Common Use Cases
null
Resetting or clearing a variable:
element.style = null;
Indicating missing object references:
let selectedItem = null;
APIs returning “no result”:
{ data: null }
undefined
Checking if a variable is initialized:
if (typeof x === 'undefined') { ... }
Detecting missing object properties:
if (obj.property === undefined) { ... }
Functions without explicit return:
function sayHi() {}
console.log(sayHi()); // undefined