Parameters, Defaults & Return Values
Design predictable function contracts with defaults, rest parameters, guard clauses, and structured results.
By the end, you’ll be able to…
- Use default parameters and rest parameters to describe optional and variable inputs.
- Validate arguments and return early when a request cannot be fulfilled.
- Return structured results without mutating the caller's data.
01Defaults make optional inputs explicit
A default parameter gives a parameter a value when the caller omits it or passes undefined. It is written with an equals sign in the parameter list. The default expression runs at call time, from left to right, so later parameters can use earlier ones. Defaults make optional inputs visible in the function signature instead of hiding a fallback deep in the body. A caller who supplies no second argument still gets a useful result.
A default is not a type check. Passing null, 0, an empty string, or another value still replaces the default. Decide which values your function accepts, then either document them or validate them. Keep the default simple enough that a reader can predict it without tracing several branches.
02Rest parameters collect the remaining arguments
A rest parameter collects any remaining arguments into a real array. It is written with three dots before the last parameter and must come last. Unlike the older arguments object, the rest parameter is an ordinary array, so map, filter, and reduce work on it directly. If the values already exist in a list, spread that list at the call site instead of rewriting the function.
Rest parameters are useful for functions that accept a variable number of inputs, such as a score summary. Validate the array before reducing it. Calling average() with no arguments would otherwise divide by zero and return NaN, which is a value but rarely a useful answer.
03Validate early, return early
A guard clause checks an invalid condition at the top of a function and returns or throws immediately. This keeps the main path unindented and makes the contract clear: the function says what it will not accept before showing what it does. Prefer a specific error such as RangeError or TypeError over a generic failure.
Returning early is also useful for valid but terminal cases. If a list is empty, return an empty result instead of wrapping the rest of the body in an if statement. Every path should return the same kind of value, so callers do not need to guess whether they received a number, a string, or undefined. A thrown error suits a caller's programming mistake, while a returned error value suits input that is expected to be invalid sometimes.
04Return one clear shape and leave arguments alone
When a function must report several related values, return one object rather than several unrelated globals. An object gives each result a name and keeps the values together. Document the shape in the function name or a short comment, and always include the same keys on every return path.
Avoid changing an argument that belongs to the caller. Methods such as sort and reverse mutate arrays in place. Copy first with spread or slice if the caller still needs the original order. A clear function contract states what goes in, what comes out, what can fail, and what the function is allowed to change. If that contract changes, update every caller and every test at the same time.
The ideas worth keeping.
- Defaults document optional inputs, while rest parameters gather a variable number of values.
- Guard clauses reject bad input early and keep the successful path readable.
- Return one consistent object shape and avoid mutating arrays or objects owned by the caller.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Build a profile object
Write buildProfile(name, role = 'learner', ...skills) that trims the name, throws an Error when the trimmed name is empty, and returns an object with name, role, and skills. Call it once with skills and once without.
Explore a worked solution
function buildProfile(name, role = 'learner', ...skills) { const cleanName = name.trim(); if (cleanName === '') { throw new Error('A name is required'); } return { name: cleanName, role, skills };}console.log(buildProfile(' Ada ', 'engineer', 'SQL', 'JavaScript'));console.log(buildProfile('Lin'));The rest parameter gathers every skill after the first two arguments. Trimming before the check prevents a string of spaces from passing validation. The returned object always has the same three keys, so callers can rely on its shape.
Exercise 2: Split a bill
Write splitBill(total, people = 2, tipRate = 0.1) that throws a RangeError if total is negative or people is not a positive integer. Return an object with tip, subtotal, and perPerson, rounded to cents. Test splitBill(80, 4).
Explore a worked solution
function splitBill(total, people = 2, tipRate = 0.1) { if (!Number.isFinite(total) || total < 0) { throw new RangeError('total must be a non-negative number'); } if (!Number.isInteger(people) || people < 1) { throw new RangeError('people must be a positive integer'); } const tip = total * tipRate; const subtotal = total + tip; const perPerson = subtotal / people; return { tip: Math.round(tip * 100) / 100, subtotal: Math.round(subtotal * 100) / 100, perPerson: Math.round(perPerson * 100) / 100, };}console.log(splitBill(80, 4));The guards make the accepted domain explicit before any arithmetic runs. Rounding each result to two decimals avoids displaying long floating-point tails. The output is { tip: 8, subtotal: 88, perPerson: 22 }.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Build a profile object
Write buildProfile(name, role = 'learner', ...skills) that trims the name, throws an Error when the trimmed name is empty, and returns an object with name, role, and skills. Call it once with skills and once without.
{"name":"Ada","role":"engineer","skills":["SQL","JavaScript"]}
{"name":"Lin","role":"learner","skills":[]}Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.