Give one operation a reusable interface
A function receives arguments, performs an operation and can return a result. Keep input assumptions explicit. A function returning a calculated value is easier to test than one that silently modifies unrelated page state.
function percentage(earned, maximum = 100) {
if (!Number.isFinite(earned) || !Number.isFinite(maximum) || maximum <= 0) {
throw new RangeError('Use finite numbers and a positive maximum');
}
return (earned / maximum) * 100;
}
const formatResult = function (value) {
return value.toFixed(1) + '%';
};
console.log(formatResult(percentage(42, 50))); // 84.0%The declaration names percentage. The expression creates a function and stores it in formatResult. A default parameter applies when the supplied argument is undefined or omitted, not when it is null. A missing return normally produces undefined.
Rest parameters
function sum(...values) {
return values.reduce((total, value) => total + value, 0);
}
console.log(sum(2, 3, 4)); // 9
console.log(sum()); // 0Rest collects remaining arguments into a real array. This small sum assumes numeric inputs; add validation if untrusted values can reach it. Rest must be the last parameter.
Arguments and mutation
Arguments are passed as values. When that value is an object reference, a function can mutate the same object the caller observes. Reassigning a parameter to a new object does not reassign the caller's variable. Prefer returning a new object when mutation is unnecessary, and document intentional updates.
Declaration timing
A function declaration can generally be called earlier in its scope. A function expression assigned to const cannot be called before that binding is initialized. This affects code organization but is not a reason to depend on confusing ordering.
Practice
- Write a function returning the larger of two numbers and test equal values.
- Call percentage with maximum zero and confirm its error path.
- Explain the difference between passing a function and calling it: handler versus handler().
- Write a function that returns a result rather than printing it, then test the return value separately from UI rendering.