Too Few Arguments: Undefined Parameters
What you'll learn: What happens when you call a function with fewer arguments than it has parameters.
When you define a function with parameters but call it without providing all the expected arguments, JavaScript doesn't throw an error. Instead, it assigns undefined to any parameters that didn't receive a value.
How It Works
Think of function parameters like empty boxes waiting to be filled. If you don't hand over enough items when calling the function, some boxes remain empty — and in JavaScript, "empty" means undefined.
function greet(firstName, lastName) {
console.log(firstName); // "Alice"
console.log(lastName); // undefined
}
greet("Alice"); // Called with only 1 argument, needs 2
In this example, firstName gets the value "Alice", but lastName receives nothing, so it defaults to undefined.
Why This Matters
This behavior can lead to unexpected results if you're not careful:
function add(a, b) {
return a + b;
}
console.log(add(5)); // NaN (5 + undefined = NaN)
JavaScript won't warn you — it simply uses undefined for the missing parameter, which often produces bugs rather than errors.
Defensive Coding
You can check for this situation:
function multiply(x, y) {
if (y === undefined) {
console.log("Warning: second parameter missing!");
return 0;
}
return x * y;
}
Key Takeaway: When you call a function with fewer arguments than parameters, JavaScript automatically assigns undefined to the missing parameters — no error is thrown, so always ensure you're passing the expected number of arguments.