Sub topic 2
What Happens with Missing or Extra Arguments
This chapter assumes you can declare and call functions, use let and const, work with arrays and objects, and read template literals. You should also know the difference between a parameter (the name in the function definition) and an argument (the value passed in the call), which the previous chapter covered.
Many languages refuse to compile or run a call whose argument count doesn't match the function's parameter list. JavaScript performs no such check. Any function can be called with any number of arguments, and the engine follows two fixed rules to reconcile the mismatch. Knowing those rules lets you predict what a function receives, and it explains a family of bugs that otherwise look mysterious.
The Binding Rules
When a function is called, JavaScript pairs arguments with parameters by position: the first argument goes to the first parameter, the second to the second, and so on.
- Missing arguments: any parameter with no matching argument is bound to
undefined. - Extra arguments: any argument beyond the last parameter has no parameter name. It is still passed to the function, but you can't reach it through a named parameter.
function describe(a, b) {
return `a=${a}, b=${b}`;
}
console.log(describe(1)); // "a=1, b=undefined"
console.log(describe(1, 2, 3)); // "a=1, b=2" (the extra argument is ignored)
console.log(describe()); // "a=undefined, b=undefined"None of these calls throws an error. The engine does not warn you, and linters only catch some cases.
Missing Arguments in Practice
A missing argument doesn't fail where it is missing. It fails later, wherever the code first uses the undefined value. That gap between cause and symptom makes these bugs slow to track down. The three most common symptoms are shown below.
function total(price, taxRate) {
return price + price * taxRate;
}
function greet(name) {
return `Hello, ${name}!`;
}
function getCity(user) {
return user.address.city;
}
console.log(total(100)); // NaN, because 100 * undefined is NaN
console.log(greet()); // "Hello, undefined!"
try {
getCity();
} catch (err) {
console.log(err.constructor.name); // "TypeError"
console.log(err.message); // "Cannot read properties of undefined (reading 'address')"
}| Symptom | Typical cause | Where it surfaces |
|---|---|---|
| `NaN` in a calculation | Arithmetic with an `undefined` operand | Often far downstream, after the value spreads through other calculations |
| The text `"undefined"` in output | String conversion of a missing value | In UI text, logs, URLs, or file names |
| `TypeError: Cannot read properties of undefined` | Property access on a missing object | At the first `.` after the parameter |
The NaN case is the hardest to catch. NaN passes through every later arithmetic operation without throwing, so the bad value can reach a database or a rendered page before anyone notices.
The exact TypeError message varies between engines. The text shown above is from V8, the engine in Chrome and Node.js. Firefox words it differently.
Missing versus explicitly undefined
Inside the function, a missing argument and an explicit undefined look identical through the parameter:
function show(x) {
return x === undefined;
}
console.log(show()); // true
console.log(show(undefined)); // trueIf you really need to tell these two cases apart, you have to count the arguments themselves, which a later chapter on the arguments object and rest parameters covers. In practice, well-designed APIs treat the two cases as the same, and JavaScript's default parameters follow that convention too.
Skipping a parameter in the middle
Because binding is positional, you can't leave out the second of three arguments and still supply the third. You have to fill the slot:
function makeLabel(text, color, size) {
return `${text} (${color ?? "black"}, ${size ?? "medium"})`;
}
console.log(makeLabel("Save", undefined, "large")); // "Save (black, large)"An empty slot such as makeLabel("Save", , "large") is a syntax error. A trailing comma, as in makeLabel("Save",), is allowed and adds no argument. This positional limit is one reason to put optional parameters last, and, when there are several of them, to accept an options object instead (covered later in this tutorial).
Checking for Missing Arguments
When a parameter must be present, check for it at the top of the function and fail with a clear message. Choose the check deliberately:
function scale(value, factor) {
if (value === undefined) {
throw new TypeError("scale: value is required");
}
if (factor == null) {
// == null matches both undefined and null
factor = 1;
}
return value * factor;
}
console.log(scale(5)); // 5
console.log(scale(5, null)); // 5
console.log(scale(5, 3)); // 15Extra Arguments in Practice
Ignoring extra arguments seems harmless, but it causes a classic bug with callbacks. Array methods such as map, forEach, and filter call your callback with three arguments: the element, its index, and the array. Your function receives all three, whether or not it expects them.
const inputs = ["1", "2", "3"];
console.log(inputs.map(parseInt)); // [1, NaN, NaN]parseInt takes two parameters, (string, radix), so map passes the index as the radix:
| Call made by `map` | Radix | Result |
|---|---|---|
| `parseInt("1", 0)` | 0 means "infer the base", so base 10 | `1` |
| `parseInt("2", 1)` | Base 1 is invalid | `NaN` |
| `parseInt("3", 2)` | In base 2, the digit 3 is invalid | `NaN` |
To fix it, control exactly which arguments reach the function:
const inputs = ["1", "2", "3"];
console.log(inputs.map((s) => parseInt(s, 10))); // [1, 2, 3]
console.log(inputs.map(Number)); // [1, 2, 3]Number works because it reads only its first argument and ignores the rest.
The maintenance hazard
Passing a named function directly as a callback (items.map(format)) works only as long as format ignores its second and third parameters. If someone later adds an optional second parameter to format, every such call site quietly starts passing an index into it. No error is thrown, and the output simply changes. Wrapping the call in an arrow function, items.map((item) => format(item)), pins the argument list and protects the call site from future signature changes.
Summary of the Rules
- JavaScript never checks how many arguments a call passes.
- Unfilled parameters are
undefined. Symptoms show up where the value is first used. - Extra arguments are not bound to any parameter name, but they are still passed. Callback APIs that pass extra values can trigger bugs because of this.
- A missing argument and an explicit
undefinedare indistinguishable through the parameter.
Exercise
What does ["10", "10", "10"].map(parseInt) return, and why?
Show answer
It returns [10, NaN, 2]. The map method passes the index as parseInt's radix. parseInt("10", 0) infers base 10 and gives 10. parseInt("10", 1) gives NaN because base 1 is invalid. parseInt("10", 2) reads "10" in binary and gives 2.
Exercise
Given function area(w, h) { return w * h; }, what do area(3), area(3, 4, 5), and area() return?
Show answer
area(3) returns NaN because h is undefined and 3 undefined is NaN. area(3, 4, 5) returns 12 because the third argument is not bound to any parameter. area() returns NaN because undefined undefined is NaN. None of the three calls throws an error.
Exercise
A function starts with if (!count) throw new Error("count is required");. Why is this check flawed, and what should replace it?
Show answer
The check rejects valid falsy values. A call that passes count as 0 would throw, even though 0 is a legitimate count. Replace it with if (count === undefined), or with if (count == null) if null should also count as missing.