null and undefined
JavaScript · Reference cheat sheet
null and undefined
JavaScript · Reference cheat sheet
📋 Overview
JavaScript has two empty-ish values: undefined (missing / not set) and null (intentional empty). Beginners should treat them as related but not identical, and prefer strict equality.
🔧 Core concepts
| Value | Usual meaning | How you get it |
|---|---|---|
undefined | Not assigned / missing property / no return | Default state |
null | Deliberate “no object” | You (or an API) set it |
== | Loose equality | null == undefined is true |
=== | Strict equality | Prefer this |
Optional chaining (?.) and nullish coalescing (??) help handle both safely.
💡 Examples
undefined by default:
let x;
console.log(x); // undefined
console.log(typeof x); // undefined
function f() {}
console.log(f()); // undefinednull as intentional empty:
let user = null;
if (user === null) {
console.log("logged out");
}
user = { name: "Ada" };
console.log(user.name);Loose vs strict:
console.log(null == undefined); // true
console.log(null === undefined); // false
console.log(null === null); // trueNullish coalescing and optional chaining:
const input = null;
const label = input ?? "default";
console.log(label); // default
const settings = undefined;
console.log(settings?.theme ?? "light"); // light⚠️ Pitfalls
- Prefer
===so you do not conflatenullandundefinedaccidentally. ??only falls through fornull/undefined;||also treats0,"",falseas missing.typeof nullis"object"— do not use typeof to detect null.- Reading missing nested props without
?.throws:obj.a.b.