Sub topic 2
Enforcing Required Parameters
This chapter assumes you already know how default values work and that they are evaluated on each call. It continues from that point to required arguments, variable-length argument lists, options objects, and return values.
Enforcing Required Parameters
A default expression runs only when its argument is undefined. If the default is a call to a function that throws, a missing argument becomes an error at call time.
function required(name) {
throw new Error(`Missing parameter: ${name}`);
}
function connect(url = required("url")) {
return `Connecting to ${url}`;
}
console.log(connect("https://example.com"));
try { connect(); } catch (e) { console.log(e.message); } // Missing parameter: urlThe Legacy arguments Object and Rest Parameters
Non-arrow functions get an arguments object. It holds every argument that was passed, but it is only array-like, so it has no reduce or map. Arrow functions do not have their own arguments. A rest parameter (...rest) is the modern replacement. It collects the remaining arguments into a real array.
function legacySum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) total += arguments[i];
return total;
}
function sum(first, ...rest) {
return rest.reduce((total, n) => total + n, first);
}
const numbers = [5, 10, 15];
console.log(legacySum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4)); // 10
console.log(sum(...numbers)); // 30, spread expands the array
console.log(Math.max(...numbers)); // 15Spread syntax in a call does the reverse of rest: it expands an array into separate arguments.
How Defaults and Rest Affect function.length
function.length counts only the parameters that come before the first default. A rest parameter is never counted.
| Signature | `length` |
|---|---|
| `(a, b = 2, c)` | 1 |
| `(a, ...rest)` | 1 |
Options Objects with Destructured Parameters
Destructure an options object and give each property its own default. Add = {} for the whole parameter so callers can omit the object entirely.
function createUser({ name, role = "viewer", active = true } = {}) {
return { name, role, active };
}
console.log(createUser({ name: "Ana", role: "admin" }));
console.log(createUser()); // { name: undefined, role: "viewer", active: true }Passing Primitives and Objects
JavaScript passes every argument by value. When the argument is an object, the value being copied is a reference to that object. As a result, a mutation inside the function is visible to the caller, but reassigning the parameter is not.
function update(count, user) {
count = count + 1; // local only
user.name = "Bo"; // caller sees this
user = { name: "Cy" }; // local only
}
let n = 1;
const u = { name: "Al" };
update(n, u);
console.log(n, u.name); // 1 "Bo"Returning Values and the Implicit undefined
A function with no return statement, or with a bare return;, returns undefined. A common bug is calling such a function and using its result as if it held data.
Exercise
What do f.length and f() return for function f(a = 1, ...xs) { xs.push(a); }?
Show answer
f.length is 0, because the first parameter already has a default and rest parameters are never counted. f() returns undefined, because the function has no return statement.
Exercise
Inside function g(list) { list = [...list, 4]; }, does calling g(arr) change arr?
Show answer
No. The function builds a new array and reassigns only the local parameter. The caller's array is never mutated.