The parameters that a function accepts and the value that it gives back are its contract with whoever calls it. JavaScript is loose about that contract. A missing argument becomes undefined, an extra argument is ignored, and a function with no return quietly produces nothing at all. Understanding those defaults, and designing functions that fail loudly when they are misused, is what pays off.
The previous lesson in this module covered "Declaring and Calling Functions", and the next lesson in this module is about "Arrow Functions vs Regular Functions".
What is the basic contract between caller and function?
Parameters are the names that you write in the declaration. Arguments are the values that you pass at the call site. The values are matched by position, and inside the body of the function the parameter names are bound to them.
function describe(name, role) {
return name + ' works as ' + role;
}
console.log('two arguments give', describe('Ada', 'engineer'));
console.log('three arguments give', describe('Ada', 'teacher', 'extra'));
Two things happened in the second call. The third argument was ignored completely, because the function only declared two parameters. And the arguments were matched strictly by position, so there is no way to skip the first one and supply the second.
What happens when you pass too few arguments?
The missing ones become undefined. Nothing throws, and nothing warns you. The function simply runs with undefined where a value was expected.
function describe(name, role) {
return name + ' works as ' + role;
}
console.log('both given:', describe('Ada', 'engineer'));
console.log('one given:', describe('Ada'));
console.log('none given:', describe());
That last line is rarely what anybody wants, and it fails quietly. The text conversion turns undefined into the word undefined, and then the program carries on. Two tools protect you from this class of bug. The first one is a default parameter, which the next lesson of this module covers in detail. The second one is a guard at the top of the function.
function withTax(amount, rate) {
if (typeof amount !== 'number' || Number.isNaN(amount)) {
throw new TypeError('amount must be a number');
}
return Math.round(amount * (1 + rate) * 100) / 100;
}
console.log('a good call gives', withTax(100, 0.18));
try {
withTax('100', 0.18);
} catch (error) {
console.log('caught:', error.constructor.name, '-', error.message);
}
The guard turns a silent wrong answer into an immediate and named error. That is usually the better trade. A crash at the point where the mistake happened is far cheaper than a wrong total that somebody discovers days later.
Do parameters change the caller's variables?
No. A parameter is a local binding. When you pass a simple value, the function gets a copy of it. When you pass an object, the function gets a reference to the same object, which is a different story and it is covered in the objects module of this tutorial.
function applyDiscount(total, discount) {
total = total - discount;
return total;
}
const cart = { total: 500 };
console.log('the function gives', applyDiscount(cart.total, 50));
console.log('the cart still holds', cart.total);
The assignment inside the function rebinds the parameter, and it has no effect outside the function. A common confusion is that cart.total went down to 450. It did not, and the last line proves it.
What does a function give back?
Whatever the return statement passes back. A function with no return gives back undefined, implicitly, at the end of its body.
function noReturn() {
const value = 42;
}
function earlyExit(items) {
if (items.length === 0) {
return 'empty';
}
return 'has ' + items.length + ' items';
}
console.log('noReturn gives', noReturn());
console.log('its type is', typeof noReturn());
console.log('an empty list gives', earlyExit([]));
console.log('a full list gives', earlyExit(['a', 'b']));
return also ends the function straight away. Everything after it in the same block never runs, and that is exactly what makes the early return pattern work. You check the unhappy case, you leave, and then the rest of the function deals with the normal one.
function withdraw(balance, amount) {
if (amount <= 0) {
return { ok: false, reason: 'amount must be positive' };
}
if (amount > balance) {
return { ok: false, reason: 'insufficient funds' };
}
return { ok: true, balance: balance - amount };
}
console.log('a good withdrawal:', withdraw(500, 200));
console.log('a bad withdrawal:', withdraw(500, 900));
Each branch returns a complete answer, so the caller always gets a result and never has to work out what the function did not say. Returning an object like this is better than returning a bare number, because it carries the success flag with it.
How do I return more than one value?
A JavaScript function returns exactly one value. To return several, you bundle them together. Use an object when the values have names, and use an array when they are simply a sequence.
function splitAmount(total, people) {
const each = Math.floor(total / people);
const remainder = total - each * people;
return { each: each, remainder: remainder };
}
const result = splitAmount(100, 3);
console.log('each person gets', result.each);
console.log('the remainder is', result.remainder);
An object is usually the better choice, because the property names document themselves. result.each says what the number is, while result[0] does not. When the values really are an ordered sequence and the order is obvious from the name of the function, such as a function called minAndMax that returns [min, max], an array is fine.
What is the difference between returning a value and changing something?
Some functions work out an answer and hand it back. Others change the world, by writing to the page or adding to a list or sending a request, and they return nothing useful. Keeping those two kinds apart is what makes code testable, because a function that only computes has no side effects for you to worry about.
// Pure: the same input gives the same output and nothing outside changes.
function totalPrice(items) {
let sum = 0;
for (const item of items) {
sum = sum + item.price;
}
return sum;
}
// Impure: it changes something outside itself.
function addToCart(cart, item) {
cart.push(item);
}
const cart = [];
addToCart(cart, { price: 250 });
console.log('the cart holds', cart.length, 'item');
console.log('the total price is', totalPrice(cart));
A pure function can be tested by calling it and checking the result, with no setup and nothing to clean up afterwards. An impure function has to be checked for what it changed. The best-designed functions are pure at the core, with one thin impure wrapper that does the changing.
The parameter and return rules worth remembering
- Arguments are matched by position. Missing ones become
undefined, and extra ones are ignored. - Nothing throws when an argument is missing, so validate inside the function if the value really matters.
- Parameters are local, so reassigning one never changes the variable of the caller.
- A function without a
returngives backundefined. returnends the function straight away, which is what makes early returns work.- Return one value. Bundle several values into an object with named properties.
- Returning a result object such as
{ ok, value, reason }makes the success case explicit instead of leaving the caller to guess it.
Try it yourself: write a function applyCoupon(total, coupon) that takes a coupon object shaped like { type: 'percent', value: 20 } or { type: 'flat', value: 150 } and returns the final amount. Make it handle a missing coupon, an unknown coupon type, and a negative value, and have each of those return a clear result object instead of throwing. Then call it with every case and check that each path returns something sensible, because that habit is what stops a discount function from quietly giving away a free order.