Sub topic 7
Enforcing Required Parameters
This chapter assumes you know how default parameter values work and that defaults are evaluated on every call, only when the argument is undefined. It builds on those rules to make an argument mandatory, then looks at an older way of reading arguments that you will still find in existing code.
Making a Parameter Required
JavaScript never complains about a missing argument. The parameter just becomes undefined, and the error appears later, often far from the real cause. You can make the failure happen right away by using a throwing function call as the default value.
function required(name) {
throw new Error(`Missing parameter: ${name}`);
}
function connect(url = required("url")) {
return `Connecting to ${url}`;
}
console.log(connect("https://example.com")); // "Connecting to https://example.com"
try {
connect();
} catch (err) {
console.log(err.message); // "Missing parameter: url"
}This works because a default expression runs only when it is needed. When the caller passes a URL, required("url") never runs. When the argument is missing, the default runs and throws before the function body starts.
Limits of the pattern
- It catches only
undefined. Passingnullor""gets through, so validate values inside the body if they matter. - The check happens at runtime. If you need compile-time checks, use a type checker such as TypeScript.
- Passing the parameter name as a string keeps the error message clear when several parameters use the same helper.
The Legacy arguments Object
Before rest parameters existed, functions read a variable number of arguments through arguments. Every non-arrow function gets this array-like object automatically. It holds every argument passed, whatever parameters the function declares.
function legacySum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(legacySum(1, 2, 3)); // 6Common errors with arguments
| Mistake | What happens | Fix |
|---|---|---|
| Calling `arguments.map(...)` | TypeError, because it is not a real array | `Array.from(arguments)` |
| Using `arguments` in an arrow function | It refers to the enclosing function's `arguments`, or throws a ReferenceError at the top level | Use a rest parameter |
| Assuming a missing argument appears in it | `arguments.length` counts only the arguments actually passed | Check `length` explicitly |
function firstTwo() {
const args = Array.from(arguments);
return args.slice(0, 2);
}
console.log(firstTwo("a", "b", "c")); // ["a", "b"]Exercise
Given function f(x = required("x")) { return x; }, what do f(null) and f(undefined) do, and why?
Show answer
f(null) returns null because null is not undefined, so the default never runs. f(undefined) throws "Missing parameter: x" because an explicit undefined triggers the default, the same as omitting the argument.
Exercise
Why does const count = () => arguments.length; fail when it is defined at the top level of a module?
Show answer
Arrow functions have no arguments object of their own. At the top level there is no enclosing function to borrow one from, so arguments is not defined and calling count() throws a ReferenceError. Use (...args) => args.length instead.