Programming (JavaScript basics) → Lesson 5

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

  1. Implement clamp and test with values above, below, and inside range.
  2. Write formatName that trims inputs; test with extra spaces.
  3. Create parseIntSafe that returns a number or null. Test with '10' → 10, 'x' → null.

Common mistakes

  • Forgetting to return a value — the function returns undefined.
  • Relying on outer mutable state instead of passing inputs.
  • Using side-effecting code inside otherwise pure functions.