Sub topic 7
Enforcing Required Parameters
This chapter assumes you already know two rules from earlier chapters. A default value is used only when the argument is undefined, and the default expression is evaluated each time the function is called, when it is needed. Together these rules give you a short way to make a parameter mandatory.
The Problem: Silent `undefined`
JavaScript never complains about a missing argument. The parameter becomes undefined and the function keeps running. The failure, if one happens, shows up later and farther from its cause:
function connect(url) {
return `Connecting to ${url.toUpperCase()}`;
}
try {
connect();
} catch (err) {
console.log(err.message); // "Cannot read properties of undefined (reading 'toUpperCase')"
}That message says nothing about a missing url. In a larger function, the undefined might travel through several calls before something breaks. A required-parameter check moves the failure to the function's entry point and gives it a clear message.
The Throwing-Default Pattern
The default expression runs only when the argument is missing. If that expression calls a function that throws, a missing argument becomes an immediate, descriptive error:
function required(name) {
throw new TypeError(`Missing required parameter: ${name}`);
}
function connect(url = required("url"), timeout = 5000) {
return `Connecting to ${url} (timeout ${timeout}ms)`;
}
console.log(connect("https://example.com"));
// "Connecting to https://example.com (timeout 5000ms)"
try {
connect();
} catch (err) {
console.log(err.name, err.message); // "TypeError Missing required parameter: url"
}When the caller supplies url, required("url") never runs, so the check costs nothing. TypeError is the conventional error type for a bad or missing argument, though a plain Error also works.
Why you need a helper function
You might try putting throw directly in the parameter list. That is a syntax error, because throw is a statement and a default must be an expression:
// SyntaxError: Unexpected token 'throw'
// function connect(url = throw new Error("url required")) {}Calling a function is an expression, so wrapping the throw in required() makes it legal. An inline arrow that you call immediately also works, but it is harder to read:
function connect(url = (() => { throw new TypeError("url required"); })()) {
return url;
}Define one required helper in a shared utility module and use it everywhere.
What the Check Catches and What It Misses
The check follows the default rules exactly, so it fires only for undefined:
| Call | Value of `url` | Throws? |
|---|---|---|
| `connect()` | missing | Yes |
| `connect(undefined)` | `undefined` | Yes |
| `connect(null)` | `null` | No |
| `connect("")` | `""` | No |
| `connect(0)` | `0` | No |
Here is a version that combines both checks:
function required(name) {
throw new TypeError(`Missing required parameter: ${name}`);
}
function connect(url = required("url")) {
if (typeof url !== "string" || url.length === 0) {
throw new TypeError(`url must be a non-empty string, got ${JSON.stringify(url)}`);
}
return `Connecting to ${url}`;
}
try {
connect(null);
} catch (err) {
console.log(err.message); // "url must be a non-empty string, got null"
}Evaluation Order and Side Effects
Parameters are initialized from left to right, and all of them are initialized before the body starts. This has two consequences.
First, when several required parameters are missing, the leftmost one is the one reported:
function required(name) {
throw new TypeError(`Missing required parameter: ${name}`);
}
function transfer(from = required("from"), to = required("to"), amount = required("amount")) {
return `${amount} from ${from} to ${to}`;
}
try {
transfer();
} catch (err) {
console.log(err.message); // "Missing required parameter: from"
}Second, the body never runs when the check fails. No logging, counter updates, or partial writes happen before the error. Validation written inside the body has the same guarantee only if you place it before any side effects.
A required parameter can also come after an optional one, and an earlier parameter can provide the message context:
function required(name) {
throw new TypeError(`Missing required parameter: ${name}`);
}
function send(channel = "default", message = required(`message for ${channel}`)) {
return `[${channel}] ${message}`;
}
try {
send("alerts");
} catch (err) {
console.log(err.message); // "Missing required parameter: message for alerts"
}Required Properties in Options Objects
The pattern also works inside destructured parameters. This is where it helps most, because options objects tend to grow many properties:
function required(name) {
throw new TypeError(`Missing required parameter: ${name}`);
}
function createUser({ name = required("name"), role = "viewer" } = {}) {
return { name, role };
}
console.log(createUser({ name: "Ana" })); // { name: "Ana", role: "viewer" }
try {
createUser({ role: "admin" });
} catch (err) {
console.log(err.message); // "Missing required parameter: name"
}
try {
createUser();
} catch (err) {
console.log(err.message); // "Missing required parameter: name"
}The = {} on the whole parameter matters. Without it, createUser() would try to destructure undefined and throw "Cannot destructure property 'name' of 'undefined'", which is the vague kind of error this pattern exists to replace.
Side Effect on `function.length`
function.length counts only the parameters before the first one with a default. A throwing default counts as a default, so the required parameter disappears from the count:
function required(name) {
throw new TypeError(`Missing required parameter: ${name}`);
}
function plain(url, timeout) {}
function guarded(url = required("url"), timeout) {}
console.log(plain.length); // 2
console.log(guarded.length); // 0Most code never reads length. Code that does, such as some currying helpers and argument-count-based dispatch, will treat guarded as taking no arguments. If you depend on such a library, check the parameter in the body instead.
Choosing an Approach
| Approach | Catches missing at | Catches wrong type | Cost |
|---|---|---|---|
| No check | Later, with a vague error | No | None |
| Throwing default | Call time, before the body | No | Changes `length` |
| Explicit check in body | Call time | Yes, if you write it | More lines |
| TypeScript or JSDoc with type checking | Before the code runs | Yes, at compile time | Build tooling; no runtime protection |
Static types and runtime checks work well together. Types catch mistakes in your own code before it runs. Runtime checks protect public functions that are called from plain JavaScript, configuration files, or network data.
Exercise
Given function f(a = required("a"), b = required("b")) { return a + b; } and the helper required from this chapter, what happens for each call: f(1), f(undefined, 2), f(null, null), and f(1, 2)? What does f.length return?
Show answer
f(1) throws "Missing required parameter: b". f(undefined, 2) throws "Missing required parameter: a", because an explicit undefined triggers the default. f(null, null) returns 0, because null does not trigger defaults and null + null is 0. f(1, 2) returns 3. f.length is 0, because the first parameter already has a default.
Exercise
Write function sendEmail(options) that destructures to (required), subject (required), and body (default ""), so that sendEmail() with no arguments throws "Missing required parameter: to" rather than a destructuring error.
Show answer
function sendEmail({ to = required("to"), subject = required("subject"), body = "" } = {}) { return { to, subject, body }; }. The = {} default lets the call with no arguments destructure an empty object. Properties are then initialized left to right, so the check for to throws first.