Tutorials JavaScript null & undefined
Ch 9 / 78
Chapter 12 Beginner 5 min read JavaScript

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.

What you'll learn
What null and undefined represent and when each appears
The key differences between the two — type, origin, and intent
Loose vs strict equality — why null == undefined is true
Safe-check patterns — != null, optional chaining ?., nullish coalescing ??
Common pitfalls — typeof null bug, missing returns, uninitialised variables
Best-practice patterns for working with absent values in real projects

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
typeof → "object" ⚠️
An intentional empty value. A developer explicitly sets a variable to 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
typeof → "undefined" ✓
An automatic absence. JavaScript assigns 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.
JavaScript — First Look
// 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); // false
The typeof null Bug
typeof 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)
JavaScript — Key Differences in Code
// 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:

Uninitialised Variable
A variable declared with let or var but not assigned a value.
let x; // undefined
Missing return Value
A function that has no return statement, or returns with no value.
function f(){} → undefined
Missing Object Property
Reading a property that does not exist on an object.
obj.missing → undefined
Missing Function Argument
Calling a function without providing all its expected arguments.
fn(1) — 2nd param → undefined
Intentional Reset
Developer explicitly clears a value — e.g., logout clears the user reference.
user = null;
Initial Empty State
A variable is declared and deliberately set to null because it will be filled later.
let cart = null;
DOM / API Returns
Methods like getElementById or API calls return null when nothing is found.
document.getElementById("x")
End of Prototype Chain
The very top of every prototype chain is null.
Object.getPrototypeOf
(Object.prototype)
JavaScript — All the Ways They Appear
// ── 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:

null == undefined true The only special case — they are loosely equal to each other
null === undefined false Strict equality — different types, always false
null == 0 false null is not loosely equal to 0
null == false false null is not loosely equal to false
null == "" false null is not loosely equal to empty string
undefined == 0 false undefined is not loosely equal to 0
undefined == false false undefined is not loosely equal to false
val != null pattern True only when val is neither null nor undefined — the canonical guard
JavaScript — Equality Examples
// 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!
Pro Tip
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:

val != null
Canonical check — true when val is neither null nor undefined. The one acceptable use of ==.
if (user != null) { … }
val === null
Strict check for exactly null. Use when you need to distinguish null from undefined.
if (result === null) reset();
val === undefined
Strict check for exactly undefined. Safer than typeof for local variables.
if (arg === undefined) arg = 0;
obj?.prop
Optional chaining — safely reads nested properties. Returns undefined instead of throwing if obj is null/undefined.
user?.address?.city
val ?? default
Nullish coalescing — returns right side only when val is null or undefined. Keeps 0 and "".
score ?? 0
??= assignment
Logical nullish assignment (ES2021) — assigns only if current value is null or undefined.
user.name ??= "Guest";
JavaScript — Safe-Check Patterns
// ── 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:

JavaScript — Pitfalls & Fixes
// ❌ 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}' ✓
Note
When sending data to an API, if a field should be explicitly absent but still present in the payload, use 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 ??.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

Everyday utilities for handling absent values cleanly in real-world JavaScript:

JavaScript — Practical Recipes
// ── 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}'
⚡
Free Resource
Download our JavaScript Cheat Sheet
null, undefined, optional chaining & nullish coalescing — all on one page.
Get Sheet
Quick Check
What does typeof null return in JavaScript?
Quick Check
What is the output of 0 ?? "default"?
Quick Check
Which expression catches both null and undefined?
Chapter Summary
  • null is an intentional empty value set by the developer. undefined is assigned automatically by JavaScript for uninitialised variables, missing properties, and functions with no return.
  • typeof null returns "object" — a historical bug that was never fixed. Always use === null to check for null.
  • null == undefined is true (loose equality). null === undefined is false (strict equality).
  • val != null is the canonical single check that guards against both null and undefined.
  • 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 preserves 0 and "".
  • JSON.stringify omits undefined values from objects but preserves null. Use null when the key must stay in the payload.
  • In arithmetic, null coerces to 0 while undefined coerces to NaN.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel