Programming Lesson 5: Functions
How to write reusable blocks of code, name them, and test them reliably.
Learning goals
- Define what a function is and when to use one.
- Distinguish parameters vs arguments and return values vs logging.
- Understand scope, guard clauses, and single-responsibility naming.
- Test functions manually with example calls.
What is a function?
A function is a reusable block of code that performs a task and optionally returns a value. Functions accept parameters (named inputs) and are called with arguments (the actual values).
Parameters vs arguments
Parameters are variable names in a function definition. Arguments are the concrete values passed when calling the function.
Return value vs printing/logging
Prefer returning values from functions so callers can use results. Logging is useful for debugging but not for composing behavior.
Scope
Variables declared inside a function are local and not visible outside. Functions can read outer variables (closure) but relying on outer mutable state makes testing harder.
let x = 5; // outer
function add(y) { // y is local
return x + y; // reads outer x
}
Guard clauses / early return
Use early returns to keep code flat and readable instead of nested conditionals.
function divide(a, b) {
if (b === 0) return null; // guard
return a / b;
}
function toNumber(value) {
const n = Number(value);
return Number.isNaN(n) ? null : n;
}
toNumber('42'); // 42
toNumber('abc'); // null
Testing functions (manual)
Call functions with representative inputs and check return values. Keep tests small and deterministic.
console.assert(clamp(5,0,10) === 5);
console.assert(clamp(-1,0,10) === 0);
console.assert(formatName('A','B') === 'A B');
Practice tasks
- Implement
clampand test with values above, below, and inside range. - Write
formatNamethat trims inputs; test with extra spaces. - Create
parseIntSafethat returns a number ornull. Test with '10' → 10, 'x' → null.
Common mistakes
- Forgetting to
returna value — the function returnsundefined. - Relying on outer mutable state instead of passing inputs.
- Using side-effecting code inside otherwise pure functions.