Both represent "no value," but with different intent and origin.
Both represent "no value," but with different intent and origin.
undefined: the absence of a value, usually set by the JavaScript engine — a declared-but-unassigned variable, a missing object property, a function parameter you didn't pass, or a function with no return.null: an intentional "empty" value that you assign to say "deliberately nothing here."let a; // undefined — declared, not assigned
const obj = {};
obj.missing; // undefined — property doesn't exist
function f() {}
f(); // undefined — no return
const b = null; // null — you chose to empty it
null == undefined; // true — loose equality treats them as equal
null === undefined; // false — different types
typeof undefined; // "undefined"
typeof null; // "object" (historical bug)
const value = input ?? "default"; // defaults on EITHER null or undefined
user?.address?.city; // optional chaining — undefined if any link is null/undefined
Use null to deliberately clear a value (e.g. "no selected user"), and treat undefined as "not set yet." The operators ?? (nullish coalescing) and ?. (optional chaining) handle both at once, which is why they're so widely used.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate