Code Reference

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

ValueUsual meaningHow you get it
undefinedNot assigned / missing property / no returnDefault state
nullDeliberate “no object”You (or an API) set it
==Loose equalitynull == undefined is true
===Strict equalityPrefer 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());          // undefined

null 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);      // true

Nullish 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 conflate null and undefined accidentally.
  • ?? only falls through for null/undefined; || also treats 0, "", false as missing.
  • typeof null is "object" — do not use typeof to detect null.
  • Reading missing nested props without ?. throws: obj.a.b.

On this page