null & undefined
JavaScript has two distinct values for "nothing" —
null and undefined.
They look similar but mean very different things.
Knowing when each appears and how to handle them safely is essential for writing
bug-free JavaScript.
null and undefined represent and when each appears
null == undefined is true
!= null, optional chaining ?., nullish
coalescing ??
typeof null bug, missing returns, uninitialised variables
null vs undefined — at a Glance
Both values represent the absence of a meaningful value, but they have different origins and different intentions. Think of it this way:
null to say "this slot exists but currently holds nothing."
It signals deliberate emptiness — like a cleared shopping cart or a logged-out user.
undefined
when a variable is declared but not yet given a value, when a function returns
nothing, or when you read a property that doesn't exist.
// null — intentionally set by the developer
let user = null; // no user logged in yet
let cart = null; // cart cleared on logout
// undefined — assigned automatically by JavaScript
let score; // declared but not initialised → undefined
console.log(score); // undefined
// typeof reveals their hidden types
typeof null; // "object" ← historical bug in JS!
typeof undefined; // "undefined"
// Both are falsy
Boolean(null); // false
Boolean(undefined); // falsetypeof null returns "object" — this is a famous historical
bug
in JavaScript that was never fixed to preserve backward compatibility.
null is not an object. Never use typeof to check for
null — use === null instead.
Key Differences
Here is a side-by-side comparison of the most important
differences between null and
undefined:
| Property | null | undefined |
|---|---|---|
| Who assigns it | Developer (intentional) | JavaScript engine (automatic) |
| typeof | "object" ⚠️ (bug) | "undefined" |
| Falsy? | Yes | Yes |
| null == undefined | true — loose equality treats them as equal | |
| null === undefined | false — strict equality sees them as different | |
| JSON.stringify | null → "null" | undefined → omitted |
| Arithmetic | null + 1 → 1 (coerces to 0) | undefined + 1 → NaN |
| Best used for | Intentional reset / empty state | Unset / missing values (JS-assigned) |
// typeof comparison
typeof null; // "object" ← historical bug
typeof undefined; // "undefined" ← correct
// Equality
null == undefined; // true — loose (==) treats them as equal
null === undefined; // false — strict (===) does not
null == 0; // false — null only == null/undefined
null == false; // false — same rule
// Arithmetic coercion
null + 1; // 1 (null → 0)
undefined + 1; // NaN (undefined → NaN)
null * 5; // 0
undefined * 5; // NaN
// JSON behaviour
JSON.stringify({ a: null, b: undefined });
// '{"a":null}' — undefined key is omitted!When Does Each Value Appear?
Understanding the exact scenarios that produce each value helps you predict and handle them correctly in real code:
let or var but not assigned a value.
return statement, or returns with no value.
null because it will be
filled later.
getElementById or API calls return null when
nothing is found.
null.
(Object.prototype)
// ── undefined scenarios ─────────────────────────────────────
let x; // undefined — uninitialised
const obj = { a: 1 };
console.log(obj.z); // undefined — missing property
function greet(name) {
console.log(name); // undefined — arg not passed
}
greet(); // logs undefined
function noReturn() {}
console.log(noReturn()); // undefined — no return value
const arr = [1, 2, 3];
console.log(arr[99]); // undefined — index out of bounds
// ── null scenarios ──────────────────────────────────────────
let currentUser = null; // intentional empty
currentUser = { name: "Alice" }; // assigned later
currentUser = null; // cleared on logout
// DOM returns null for missing elements
const el = document.getElementById("no-such-id");
console.log(el); // null
// Top of prototype chain
Object.getPrototypeOf(Object.prototype); // null
Equality Deep Dive
The loose equality operator ==
has a special rule: null and
undefined are only loosely equal to
each other — not to 0, "",
or false. This makes
!= null a very handy guard:
// Loose equality (==) special rule
null == undefined; // true — only pair that is loosely equal
null == 0; // false
null == ""; // false
null == false; // false
// Strict equality (===) — always false for cross-type
null === undefined; // false
null === null; // true
undefined === undefined; // true
// ✅ The canonical "neither null nor undefined" check
function process(val) {
if (val != null) { // catches both null AND undefined
console.log("Got value:", val);
}
}
process(null); // skipped
process(undefined); // skipped
process(0); // "Got value: 0" ← 0 passes! (important)
process(""); // "Got value: " ← empty string passes!val != null is the most concise way to check that a value is
neither null nor undefined — and it still
allows 0, "", and false through. This is one of the
few cases where using == instead of === is considered
idiomatic and acceptable.
Safe-Check Patterns
JavaScript gives you several modern tools to deal with
null and undefined
without writing verbose defensive code:
==.null.
Use when you need to distinguish null from undefined.undefined.
Safer than typeof for local variables.undefined instead of throwing if obj is null/undefined.0 and "".// ── Optional chaining (?.) ───────────────────────────────────
const user = null;
const city = user?.address?.city; // undefined (no crash!)
const zip = user?.address?.zip ?? "00000"; // "00000" fallback
// Optional chaining with methods
user?.getProfile?.(); // safe method call — skipped if null
// Optional chaining with arrays
const items = null;
items?.[0]; // undefined (no error)
// ── Nullish coalescing (??) ───────────────────────────────────
const score = null ?? 0; // 0
const score2 = 0 ?? 99; // 0 — 0 is kept (unlike ||)
const label = undefined ?? "N/A"; // "N/A"
// ── Nullish assignment (??=) ─────────────────────────────────
let config = {};
config.timeout ??= 3000; // assigns 3000 only if null/undefined
config.timeout ??= 5000; // 3000 stays — already set
console.log(config.timeout); // 3000
// ── Guard with != null ────────────────────────────────────────
function displayName(name) {
if (name != null) { // catches both null and undefined
return name.trim();
}
return "Anonymous";
}
displayName("Alice"); // "Alice"
displayName(null); // "Anonymous"
displayName(undefined); // "Anonymous"Common Pitfalls
These are the most frequent mistakes developers make
when working with null and
undefined:
// ❌ PITFALL 1 — using typeof to check null
typeof null === "object"; // true — the bug!
if (typeof val === "object") { … } // ← catches null too
// ✅ FIX — use === null
if (val === null) { … } // correct null check
// ❌ PITFALL 2 — accessing property on null/undefined (TypeError)
const user = null;
user.name; // TypeError: Cannot read properties of null
// ✅ FIX — optional chaining
user?.name; // undefined — no crash
// ❌ PITFALL 3 — using || for defaults, breaking on 0 or ""
function setScore(score) {
const s = score || 10; // 0 becomes 10 — wrong!
}
setScore(0); // s = 10 ← BUG: 0 is a valid score
// ✅ FIX — use ?? instead
function setScore(score) {
const s = score ?? 10; // 0 stays 0
}
setScore(0); // s = 0 ← correct!
// ❌ PITFALL 4 — forgetting JSON drops undefined
JSON.stringify({ a: 1, b: undefined }); // '{"a":1}' — b is gone!
// ✅ FIX — use null to preserve keys
JSON.stringify({ a: 1, b: null }); // '{"a":1,"b":null}' ✓
null. If a field is simply not applicable, you may omit it
entirely — but be aware that JSON.stringify silently drops
undefined values.
Try It — Live Editor
Experiment with null and
undefined below. Try changing values, removing
optional chaining, or using || vs ??.
Common Patterns & Recipes
Everyday utilities for handling absent values cleanly in real-world JavaScript:
// ── Provide default for null / undefined only ────────────────
const withDefault = (val, def) => val ?? def;
withDefault(null, "Guest"); // "Guest"
withDefault("", "Guest"); // "" ← empty string kept
withDefault(0, "Guest"); // 0 ← zero kept
// ── Safe deep property read ───────────────────────────────────
const get = (obj, path, def = undefined) =>
path.split(".").reduce((o, k) => o?.[k], obj) ?? def;
const data = { user: { address: { city: "Ahmedabad" } } };
get(data, "user.address.city"); // "Ahmedabad"
get(data, "user.phone.number", "N/A"); // "N/A"
// ── Check if value is null or undefined (nullish) ────────────
const isNullish = val => val == null;
isNullish(null); // true
isNullish(undefined); // true
isNullish(0); // false ← 0 is not nullish
isNullish(""); // false ← "" is not nullish
// ── Reset user state on logout ────────────────────────────────
let currentUser = { name: "Alice", token: "abc123" };
function logout() {
currentUser = null; // explicit reset — clear intent
}
// ── Conditional API payload ───────────────────────────────────
function buildPayload(name, age) {
return {
name, // always included
age: age ?? null, // null if not provided — keeps key
};
}
JSON.stringify(buildPayload("Bob"));
// '{"name":"Bob","age":null}'typeof null return in JavaScript?0 ?? "default"?nullis an intentional empty value set by the developer.undefinedis assigned automatically by JavaScript for uninitialised variables, missing properties, and functions with no return.typeof nullreturns"object"— a historical bug that was never fixed. Always use=== nullto check for null.null == undefinedis true (loose equality).null === undefinedis false (strict equality).val != nullis the canonical single check that guards against bothnullandundefined.- Optional chaining (
?.) safely reads nested properties without crashing when an intermediate value is null or undefined. - Nullish coalescing (
??) provides a fallback only for null/undefined — unlike||, it preserves0and"". JSON.stringifyomitsundefinedvalues from objects but preservesnull. Usenullwhen the key must stay in the payload.- In arithmetic,
nullcoerces to0whileundefinedcoerces toNaN.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.