null vs undefined
Understand two different ways JavaScript represents the absence of a value.
Learn default parameters, destructuring, JSON serialization, nullish coalescing, optional chaining, API payloads, and common interview questions.
undefined
A value has not been supplied, assigned, returned, or found. Example: let customerEmail;.
null
A developer intentionally assigns an empty value. Example: const selectedCoupon = null;.
let customerEmail;
console.log(customerEmail); // undefinedundefined means a value has not been provided or assigned yet.
const selectedCoupon = null;
console.log(selectedCoupon); // nullnull communicates that the application intentionally has no selected coupon.
function greet(name = "Guest") {
return `Hello, ${name}`;
}
greet(); // Hello, Guest
greet(undefined); // Hello, Guest
greet(null); // Hello, nullDefaults apply to undefined, not null.
JSON.stringify({
email: undefined,
phone: null
});
// {"phone":null}Undefined object properties are omitted; null properties remain in JSON.
The ?? operator falls back only for null and undefined. The || operator also treats 0 and an empty string as missing.
| Feature | undefined | null |
|---|---|---|
| Meaning | Missing or not assigned | Intentional absence |
| typeof | undefined | object (historical quirk) |
| null === undefined | false | false |
| null == undefined | true | true |
| Default parameter | Triggers default | Does not trigger default |
| Object JSON property | Omitted | Preserved |
| ?? fallback | Triggers fallback | Triggers fallback |
Best Practices and API Notes
if (product === undefined) {
return <p>Product is loading...</p>;
}
if (product === null) {
return <p>No product selected.</p>;
}undefined can mean data has not loaded; null can mean loading completed but no product exists. Define the convention consistently.
function findCustomer(id) {
const customer = database.find(item => item.id === id);
return customer ?? null;
}A lookup can consistently return either a customer object or null when no customer is found.
null vs undefined Quiz
Select an answer to see the explanation.
1. What does undefined usually communicate?
2. What does null usually communicate?
3. What does typeof null return?
4. What does a function return when it has no explicit return statement?
5. Which value triggers a default function parameter?
6. What is JSON.stringify({ email: undefined, phone: null }) likely to preserve?
7. Which operator falls back only for null or undefined?
8. What does order.customer?.shippingAddress?.city return when customer is null?
9. How can you specifically check whether a property exists when its value may be undefined?
10. What is a clear result for a failed findCustomer lookup?
Score: 0 / 10