Function signatures and missing results
Objective
Describe parameters, return values, and an explicit failure result. This course assumes you can already write JavaScript functions, loops, arrays, and objects.
Describe parameters, return values, and an explicit failure result.
Explanation
A signature describes what callers supply and what they receive. A union such as number | null expresses a result that can be absent. Callers must narrow it before arithmetic. Preconditions such as low <= high remain part of the written contract.
Returning zero for a missing value loses information when zero is a legitimate result. Choose one failure convention and cover it with a boundary test.
Runnable worked example
Compile this complete example with strict checking. The practice editor supplies the function calls; return a value rather than printing it.
function clamp(value: number, low: number, high: number): number {
return Math.min(high, Math.max(low, value));
}
const result = clamp(5, 0, 10);
Expected value of result:
5
A type alone does not establish low <= high; that remains an input precondition.
Common mistakes
Do not assume number excludes NaN or Infinity. Runtime validation is still needed at an untrusted boundary.
Guided practice
Explain each parameter and return type in the example. Predict its empty or boundary case before running it. Change one annotation to an incompatible type and read the compiler diagnostic; then restore it and change the implementation to create a behavioral bug. Explain why the two failures require different checks.
Independent practice
Recap
Describe parameters, return values, and an explicit failure result. Strict checking protects type relationships; explicit runtime checks protect external-data boundaries. Keep tests for behavior and non-mutation alongside both.