Sub topic 4
Why Defaults Apply to undefined but Not null
This chapter assumes you already know how to declare and call functions, and that you have seen the basic default parameter syntax function f(x = 1) {} from the previous chapter. Here we look at the exact rule that decides when a default is used. JavaScript checks one condition, and code that gets it wrong produces bugs that are easy to miss.
The Rule in One Sentence
A default value is used when the argument in that position is strictly equal to undefined, and in no other case.
It makes no difference whether the caller left the argument out or wrote undefined explicitly. Either way the parameter starts out as undefined, so the default runs. Every other value is kept, including null, 0, "", false, and NaN.
function greet(name = "guest", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet()); // "Hello, guest!"
console.log(greet("Ana")); // "Hello, Ana!"
console.log(greet(undefined, "Hi")); // "Hi, guest!"
console.log(greet(null)); // "Hello, null!"The last call surprises many developers. null is a real value that the caller chose to pass. The engine does not swap it out, and the template literal turns it into the text "null".
Why the Language Draws the Line Here
JavaScript has two "empty" values, and they mean different things by convention:
| Value | Conventional meaning | Typical source |
|---|---|---|
| `undefined` | No value was supplied | Missing argument, missing property, uninitialized variable, function with no `return` |
| `null` | A value was supplied, and it is deliberately empty | Set on purpose by a programmer or a data format such as JSON |
A default parameter fills in for a value that is missing. undefined is how the language itself reports that something is missing, so it is the only value that triggers a default. null says the caller considered the question and answered "nothing". Replacing that answer would throw away information.
There is a practical side as well. JSON has no undefined, so data from APIs and databases uses null for empty fields. If defaults replaced null, you could not tell "the server sent an empty field" apart from "the field was never provided".
Falsy Values Are Preserved
Before ES2015 added default parameters, people wrote defaults with ||. That pattern treats every falsy value as missing, and it is still the most common source of bugs when older code is converted.
function setVolumeOld(level) {
level = level || 50; // ES5-style default
return level;
}
function setVolume(level = 50) {
return level;
}
console.log(setVolumeOld(0)); // 50 (bug: 0 was a valid choice)
console.log(setVolume(0)); // 0 (correct)
console.log(setVolumeOld("")); // 50
console.log(setVolume("")); // ""
console.log(setVolumeOld(false)); // 50
console.log(setVolume(false)); // false| Argument passed | `x = x \ | \ | 50` | `x = 50` in signature | `x = x ?? 50` |
|---|---|---|---|---|---|
| (omitted) | 50 | 50 | 50 | ||
| `undefined` | 50 | 50 | 50 | ||
| `null` | 50 | `null` | 50 | ||
| `0` | 50 | 0 | 0 | ||
| `""` | 50 | `""` | `""` | ||
| `false` | 50 | `false` | `false` | ||
| `NaN` | 50 | `NaN` | `NaN` |
The table shows three different policies. Signature defaults replace only undefined. The nullish coalescing operator ?? replaces both undefined and null. || replaces every falsy value.
When You Also Want to Replace null
Sometimes null really should count as missing, for example when a value comes straight from JSON. The signature default cannot do this for you. Normalize the value inside the body instead:
function formatName(name) {
name ??= "guest"; // replaces null or undefined (ES2021)
return name.toUpperCase();
}
console.log(formatName(null)); // "GUEST"
console.log(formatName(undefined)); // "GUEST"
console.log(formatName("")); // "" (empty string is kept)You can keep a signature default and add ?? for null, but then the fallback is written in two places. When null must be handled, the body-only version above is usually clearer. Either way, choose one policy for each function and document it.
Edge Cases That Produce undefined
Because the check is about the value and not about how it got there, some indirect sources of undefined also trigger defaults:
function pick(a = "A", b = "B") {
return a + b;
}
const user = {};
console.log(pick(user.first, user.last)); // "AB" (missing properties are undefined)
const settings = null;
console.log(pick(settings?.left)); // "AB" (optional chaining yields undefined)
console.log(pick(...[, "x"])); // "Ax" (spreading an array hole yields undefined)
console.log(pick(void 0, "z")); // "Az" (void 0 is undefined)
function nothing() {}
console.log(pick(nothing())); // "AB" (no return means undefined)The reverse also matters. Optional chaining gives undefined when the chain is cut short, but if the property exists and holds null, you get null and the default does not run:
function label(text = "untitled") {
return text;
}
const doc1 = { meta: null };
const doc2 = { meta: { title: null } };
console.log(label(doc1.meta?.title)); // "untitled" (chain stopped at null meta)
console.log(label(doc2.meta?.title)); // null (title exists and is null)These two calls look almost the same but return different results. That is why API data is a common place for this bug to appear.
The Same Rule Applies to Destructuring
Default values inside destructuring patterns follow exactly the same undefined-only rule. A later chapter covers options objects in detail. For now, remember that one mental model covers both cases:
const { theme = "light", size = 12 } = { theme: null, size: undefined };
console.log(theme); // null
console.log(size); // 12Common Mistakes
- Expecting
nullto trigger a default. It never does. Use??in the body if it should. - Converting
||fallbacks to signature defaults without checking falsy inputs such as0and"". - Passing
nullto "skip" a middle argument. Passundefinedto skip a position and still get its default, or redesign the function to take an options object. - Assuming that optional chaining always yields
undefined. It returnsnullwhen the final property exists and holdsnull.
Exercise
Given function pad(str, width = 8, char = " ") { return String(str).padStart(width, char); }, what do pad("ab", null), pad("ab", undefined, "*"), and pad("ab", 0) return, and why?
Show answer
pad("ab", null) returns "ab": null is kept, padStart converts it to 0, and no padding is added. pad("ab", undefined, "*") returns "**ab" because undefined triggers the default width of 8. pad("ab", 0) returns "ab" because 0 is not undefined, so the default does not apply and a width of 0 adds no padding.
Exercise
An API returns { limit: null } when the user has not set a page size. Rewrite function fetchPage(limit = 20) { return limit; } so that both a missing argument and null produce 20, while 0 is still kept.
Show answer
function fetchPage(limit) { limit ??= 20; return limit; }. The ??= operator assigns only when limit is null or undefined, so fetchPage() and fetchPage(null) return 20 and fetchPage(0) returns 0. Writing limit = limit || 20 would be wrong because it also replaces 0.