Sub topic 1
What Counts as Nullish
JavaScript has two values that mean "nothing here": null and undefined. Together they are called nullish values. The optional chaining operator (?.) and the nullish coalescing operator (??) react to these two values and no others. Before using either operator, you need to know exactly which values are nullish, where they come from, and how they differ from the larger group of falsy values.
Prerequisites
This chapter assumes you already know:
- JavaScript variables, objects and arrays
- Dot (
obj.key) and bracket (obj["key"]) property access - How to call functions and methods
- Truthy and falsy values, meaning how a value behaves in an
ifcondition - The logical operators
||and&&
You can run every example in Node.js 16.9 or later, or in a modern browser console.
The Two Nullish Values
The two values are related but not interchangeable. Each one has its own conventional meaning.
| Value | Type (`typeof`) | Conventional meaning | Who usually produces it |
|---|---|---|---|
| `undefined` | `"undefined"` | A value was never assigned | The JavaScript engine |
| `null` | `"object"` (a historical bug) | Intentionally empty | Your code, APIs, JSON |
The usual rule of thumb is that undefined means "not set yet" and null means "deliberately set to nothing." The language does not enforce this rule, but most libraries and APIs follow it.
Where `undefined` comes from
You rarely write undefined yourself. The engine hands it to you in many situations:
let declared;
const obj = { a: 1 };
function noReturn() {}
function takesArg(x) {
return x;
}
console.log(declared); // undefined (declared but never assigned)
console.log(obj.b); // undefined (property does not exist)
console.log(noReturn()); // undefined (function has no return value)
console.log(takesArg()); // undefined (argument was not passed)
console.log([1, 2][5]); // undefined (index out of range)
console.log(void 0); // undefined (the void operator always yields it)Notice that reading a missing property does not throw. It quietly returns undefined. Errors start only when you try to go one level deeper, such as obj.b.c. That is the problem optional chaining solves in later chapters.
Where `null` comes from
null appears when someone chose to return or store "no value":
console.log("abc".match(/z/)); // null (no regex match)
console.log(Object.getPrototypeOf(Object.prototype)); // null (end of prototype chain)
console.log(JSON.parse('{"middleName": null}').middleName); // null (from JSON)
const session = { user: null }; // set explicitly: nobody is logged in
console.log(session.user); // nullIn the browser, document.querySelector(".missing") and localStorage.getItem("missing") also return null. JSON has no undefined, so data from a server uses null for empty fields.
Nullish Is a Subset of Falsy
A falsy value is any value that becomes false when converted to a boolean, for example in an if condition. JavaScript has a short, fixed list of them. Every nullish value is falsy, but most falsy values are not nullish.
| Value | Falsy? | Nullish? | Typical meaning |
|---|---|---|---|
| `undefined` | Yes | Yes | Not set |
| `null` | Yes | Yes | Intentionally empty |
| `false` | Yes | No | A real boolean answer |
| `0` and `-0` | Yes | No | A real number |
| `0n` | Yes | No | A real BigInt |
| `""` | Yes | No | A real, empty string |
| `NaN` | Yes | No | A failed numeric result |
| `"0"`, `"false"`, `[]`, `{}` | No | No | Ordinary truthy values |
The key insight is in the middle rows. 0, "" and false are often valid data. A volume of 0, an empty search box, and a disabled setting are all real choices a user made. Treating them like "missing" is a common source of bugs, and the next chapter looks at how || causes exactly that.
You can confirm the table with a short script:
const isNullish = (v) => v === null || v === undefined;
const samples = [
["undefined", undefined],
["null", null],
["false", false],
["0", 0],
["-0", -0],
["0n", 0n],
['""', ""],
["NaN", NaN],
['"0"', "0"],
["[]", []],
["{}", {}],
];
for (const [label, value] of samples) {
console.log(label.padEnd(10), "falsy:", !value, " nullish:", isNullish(value));
}The output shows falsy: true for the first eight rows but nullish: true only for the first two.
Testing for Nullish Values
There are several ways to check for null and undefined. They behave differently, and choosing the wrong one is a common error.
Strict equality
x === null and x === undefined each match exactly one value. Use them when the difference matters to your logic, for example when null means "the user cleared this field" and undefined means "the user never touched it."
The loose `== null` idiom
Loose equality has a special rule: null and undefined are equal to each other and to nothing else.
const values = [null, undefined, 0, "", false, NaN];
for (const v of values) {
console.log(String(v).padEnd(9), v == null);
}
// null true
// undefined true
// 0 false
// false
// false false
// NaN falseSo x == null is a compact nullish check. Many style guides ban == except for this one case. It is the same test that ?? and ?. perform internally.
Truthiness checks
if (!x) catches every falsy value, not just nullish ones. It is fine when 0, "" and false are impossible or should be rejected too. It is wrong when they are valid data.
`typeof` for undeclared variables
Reading a variable that was never declared throws a ReferenceError, even with == null. typeof is the one operator that is safe on undeclared names:
console.log(typeof notDeclaredAnywhere); // "undefined", no error
// console.log(notDeclaredAnywhere == null); // ReferenceError: notDeclaredAnywhere is not definedThis matters later. Optional chaining does not protect you from undeclared variables either. It only handles values that exist and happen to be nullish.
Missing Versus Explicitly `undefined`
A property that does not exist and a property set to undefined look the same when you read them. They are not the same.
const a = {};
const b = { x: undefined };
console.log(a.x, b.x); // undefined undefined
console.log("x" in a, "x" in b); // false true
console.log(Object.hasOwn(b, "x")); // true
console.log(Object.keys(b)); // [ 'x' ]
console.log(JSON.stringify(b)); // {}
console.log(JSON.stringify({ x: null })); // {"x":null}The difference shows up in three places:
inandObject.hasOwnreport whether the key exists, regardless of its value.Object.keys, spread, andfor...ininclude keys whose value isundefined. So{ ...defaults, ...{ x: undefined } }overwritesdefaults.xwithundefined.JSON.stringifydropsundefinedproperties but keepsnull. If a server must see "this field was cleared," sendnull.
Arrays have a similar distinction. A hole in a sparse array (such as [1, , 3]) reads as undefined but has no key, so 1 in [1, , 3] is false.
?? and ?. do not care about this distinction. They only look at the value, so a missing key and a key holding undefined are treated the same way.
Defaults That Fire Only for `undefined`
Some JavaScript features treat undefined as missing but treat null as a real value. Default parameters and destructuring defaults both work this way:
function greet(name = "guest") {
return `Hello, ${name}`;
}
console.log(greet()); // "Hello, guest"
console.log(greet(undefined)); // "Hello, guest"
console.log(greet(null)); // "Hello, null"
console.log(greet("")); // "Hello, "
const { size = 10 } = { size: null };
console.log(size); // null, the default did not applyThis surprises many developers, especially with JSON data, where empty fields arrive as null. A destructuring default will not replace them. The ?? operator covers both nullish values, which is one reason it exists. The chapter on precise defaults with ?? shows how to use it.
Common Mistakes
| Mistake | Why it fails | Better approach |
|---|---|---|
| `if (!count)` to detect "no count" | Also rejects `0` | `if (count == null)` |
| `typeof x === "object"` to detect objects | `null` passes | Add `&& x !== null` |
| `x === undefined` when data comes from JSON | JSON uses `null` | `x == null` |
| Expecting a default parameter to replace `null` | Defaults apply only to `undefined` | Use `??` inside the function |
| Assuming `obj.key === undefined` means the key is absent | The key may exist with value `undefined` | Use `Object.hasOwn(obj, key)` |
Summary
- Exactly two values are nullish:
nullandundefined. undefinedusually comes from the engine.nullusually comes from code, APIs and JSON.- Nullish values are a small subset of falsy values.
0,-0,0n,"",falseandNaNare falsy but not nullish. x == nullis the standard compact nullish check.===separates the two values when that matters.- Default parameters and destructuring defaults apply only to
undefined, not tonull.
Exercise
For each value, say whether it is falsy and whether it is nullish: 0n, null, "false", NaN, undefined, [].
Show answer
0n: falsy, not nullish. null: falsy, nullish. "false": truthy (a non-empty string), not nullish. NaN: falsy, not nullish. undefined: falsy, nullish. []: truthy, not nullish.
Exercise
A function is declared as function setVolume(level = 50) { return level; }. What do setVolume(), setVolume(0) and setVolume(null) return, and why?
Show answer
setVolume() returns 50 because the missing argument is undefined, which triggers the default. setVolume(0) returns 0 because 0 is a real value. setVolume(null) returns null because default parameters apply only to undefined, not to null.
Exercise
Given const a = {} and const b = { x: undefined }, both a.x and b.x are undefined. Name two ways to tell the objects apart, and say what JSON.stringify(b) produces.
Show answer
"x" in b is true while "x" in a is false. Object.hasOwn(b, "x") is true while Object.hasOwn(a, "x") is false. Object.keys(b) also returns ["x"]. JSON.stringify(b) produces "{}" because JSON serialization drops properties whose value is undefined.
Exercise
Why does if (typeof config === "object") not guarantee that config.port can be read safely?
Show answer
typeof null is "object", so config could be null, and reading null.port throws a TypeError. The check must also include config !== null.