Sub topic 4
null and undefined: Two Kinds of Nothing
This chapter assumes you know basic JavaScript syntax, can write functions and object literals, and have read the earlier chapters on the seven primitives and typeof. JavaScript has two values that mean "no value": undefined and null. Each is the only value of its own primitive type. They behave differently in default parameters, JSON, property checks, and numeric conversion, so confusing them causes real bugs.
The Working Model
The usual way to tell them apart is by who produces each one:
undefinedis what the language gives you when a value was never supplied. Examples are a declared but unassigned variable, a missing property, or a missing argument.nullis what a programmer or API returns on purpose to say "there is deliberately nothing here."
The engine never produces null by itself. When you see null, some code put it there.
Where undefined Comes From
let x;
console.log(x); // undefined: declared, never assigned
const settings = {};
console.log(settings.theme); // undefined: property does not exist
function echo(a) { return a; }
console.log(echo()); // undefined: argument not passed
function noReturn() {}
console.log(noReturn()); // undefined: no return statement
console.log([1, 2][5]); // undefined: index out of range
console.log(void 0); // undefined: void discards its operandWhere null Comes From
console.log("abc".match(/z/)); // null: no match
console.log(Object.getPrototypeOf(Object.prototype)); // null: end of the chain
console.log(JSON.parse('{"a": null}').a); // null: JSON has null, not undefined
let selectedUser = null; // a deliberate "nothing selected yet"
console.log(selectedUser); // nullIn a browser, document.getElementById("missing") also returns null. DOM and built-in APIs use null to mean "looked for it, found nothing."
Differences That Bite
The table summarizes how the two values behave. Later chapters explain the conversion rules in detail. For now, notice that the two values disagree almost everywhere except truthiness.
| Operation | `undefined` | `null` |
|---|---|---|
| `typeof` | `"undefined"` | `"object"` |
| `Number(value)` | `NaN` | `0` |
| `String(value)` | `"undefined"` | `"null"` |
| `Boolean(value)` | `false` | `false` |
| Triggers a default parameter | Yes | No |
| Kept by `JSON.stringify` in an object | No, the key is dropped | Yes |
| `value == null` | `true` | `true` |
| `value === null` | `false` | `true` |
Defaults Fire Only for undefined
Default parameters and destructuring defaults apply only when the value is undefined. A null passes straight through.
function greet(name = "guest") {
return `Hi, ${name}`;
}
console.log(greet()); // "Hi, guest"
console.log(greet(undefined)); // "Hi, guest"
console.log(greet(null)); // "Hi, null"
const { limit = 10 } = { limit: null };
console.log(limit); // null: the default was skippedThis often goes wrong when data comes from a JSON API, where a missing value often arrives as null. Your defaults silently stop working. The chapter on logical operators shows how ?? handles both values.
JSON Treats Them Differently
console.log(JSON.stringify({ a: undefined, b: null })); // '{"b":null}'
console.log(JSON.stringify([undefined, null])); // '[null,null]'
console.log(JSON.stringify(undefined)); // undefined (not a string)JSON has no undefined. In an object, JSON.stringify drops the key. In an array, it writes null so the indexes stay in place. A round trip through JSON can therefore turn undefined into null, or make a key disappear.
Missing Versus Explicitly undefined
Reading a property returns undefined in two cases: the property does not exist, or it exists and holds undefined. Use in or Object.hasOwn to tell the cases apart.
const config = { debug: undefined };
console.log(config.debug); // undefined
console.log(config.verbose); // undefined
console.log("debug" in config); // true
console.log("verbose" in config); // false
console.log(Object.hasOwn(config, "debug")); // true
console.log(Object.keys(config)); // [ 'debug' ]
delete config.debug;
console.log("debug" in config); // false: now truly missingArrays work the same way. A hole in a sparse array reads as undefined, but no element exists at that index:
const sparse = [, 1];
console.log(sparse[0]); // undefined
console.log(0 in sparse); // false: a hole
console.log([undefined, 1].length === sparse.length); // true, yet they differEdge Cases
undefined Is Not a Keyword
null is a literal and a reserved word. undefined is a property of the global object. Since ES5 that property cannot be overwritten, but undefined is not reserved, so you can still declare a local variable with that name:
function shadow() {
const undefined = 5;
return undefined;
}
console.log(shadow()); // 5Nobody writes this on purpose, but it explains why older code and minifiers use void 0. That expression always produces the real undefined.
typeof on Undeclared Names
Reading an undeclared variable throws a ReferenceError. typeof on the same name does not throw:
console.log(typeof notDeclaredAnywhere); // "undefined"
// console.log(notDeclaredAnywhere); // ReferenceErrorThis makes typeof a safe way to check for optional globals, such as typeof window !== "undefined" in code that runs in both browsers and Node.js. Variables declared with let and const are an exception: typeof still throws if you use it before the declaration line, while the variable is in its temporal dead zone.
Both Throw on Property Access
null and undefined are the only values that have no properties at all, not even through wrapper objects:
try {
null.length;
} catch (err) {
console.log(err instanceof TypeError); // true
}Checking for Them
const value = null;
console.log(value === undefined); // false: exactly undefined
console.log(value === null); // true: exactly null
console.log(value == null); // true: null OR undefined, nothing elsevalue == null is the one widely accepted use of loose equality. It is true only for null and undefined. It is false for 0, "", false, and NaN. The loose equality chapter explains why that rule holds.
Conventions That Keep Code Predictable
- Let
undefinedmean "not provided" and leave it to the engine. Avoid assigningundefinedyourself. - Use
nullwhen your API needs to say "no value" on purpose, such as "no user is selected." - At boundaries such as JSON, user input, and third-party APIs, treat both as empty with
value == nullor??, because you rarely control which one arrives. - Use
Object.hasOwnwhen "missing" and "set to undefined" must mean different things.
Exercise
What does this code log, and why? function pad(text, width = 8) { return String(text).padStart(width); } console.log(JSON.stringify(pad("hi", null)));
Show answer
It logs "\"hi\"". The default for width applies only to undefined, so width is null. padStart converts null to the number 0, and a target length of 0 adds no padding.
Exercise
Given const a = { x: undefined } and const b = {}, give two expressions whose results differ between a and b, even though a.x and b.x are both undefined.
Show answer
Two examples are "x" in a (true) versus "x" in b (false), and Object.keys(a).length (1) versus Object.keys(b).length (0). Object.hasOwn(a, "x") also differs. Note that JSON.stringify returns "{}" for both, because it drops undefined properties.
Exercise
A function returns user?.nickname, and the server sometimes sends nickname: null. Which single check catches every "no nickname" case without rejecting an empty string, and what are its results for null, undefined, and ""?
Show answer
The check is result == null. It is true for null, true for undefined, and false for "". Neither === null nor === undefined alone catches both empty values, and a truthiness check would also reject "".