What is the difference between null and undefined in JavaScript?
Quick Answer
undefined means a variable has been declared but not assigned, or a property/return value doesn't exist — it's the language's default “absence”. null is an explicit “no value” that you assign deliberately. typeof undefined is "undefined"; typeof null is "object" (a historic bug).
undefined is JavaScript's default for absence — a variable you declared but didn't assign, a missing argument, a property that isn't there, a function that doesn't return anything. null is a value you set on purpose to mean “intentionally empty”. A quirk to know: typeof null returns "object", which is a long-standing bug in the language. The nullish coalescing operator ?? and optional chaining ?. both treat null and undefined the same, which is usually what you want.
- Unassigned variable, missing function argument, missing object property, function with no
return→undefined. - You write
user.manager = nullto say “this user explicitly has no manager”. null == undefinedistrue;null === undefinedisfalse.- Nullish operators:
a ?? busesbonly whenaisnullorundefined(not for0/''like||).a?.bshort-circuits toundefinedifais nullish. - JSON has
nullbut notundefined—undefinedproperties are dropped onJSON.stringify.