Module 4: Functions, Scope, and Closures
Parameters, Arguments, and Return Values
Use parameters, defaults, rest parameters, and validation to make functions robust.
Parameters are names in a function definition; arguments are the values supplied when calling it. JavaScript does not enforce a fixed parameter type, so a function should document or validate the values it expects.
function greet(name = "Learner") {
return `Hello, ${name}!`;
}
console.log(greet());
console.log(greet("Asha"));
A default parameter is used when the argument is omitted or explicitly undefined, not when the argument is null.
Rest parameters#
A rest parameter gathers remaining arguments into an array:
function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
console.log(sum(2, 3, 5)); // 10
There can be only one rest parameter, and it must be the final parameter. Rest parameters are different from the spread syntax used when passing or expanding iterable values.
Validate inputs#
function calculateDiscount(price, rate) {
if (!Number.isFinite(price) || price < 0) {
throw new TypeError("price must be a non-negative finite number");
}
if (!Number.isFinite(rate) || rate < 0 || rate > 1) {
throw new RangeError("rate must be between 0 and 1");
}
return price * (1 - rate);
}
Choose error handling according to the function's contract. For form input, it may be better to return a validation result rather than throw for every expected user mistake.
Practice#
Write a function that averages any number of numeric arguments and defines what it should do when no numbers are supplied.