Functions, parameters, and scope

Turn repeated calculations into functions with clear inputs and stable returns.

Difficulty
beginner
Time
40 minutes
Last verified
9/21/2026

What you will build

Turn repeated calculations into functions with clear inputs and stable returns.

Understand the idea first

Turn repeated calculations into functions with clear inputs and stable returns.

Build it step by step

function percent(done, total) {
  if (total <= 0) return 0;
  return Math.round((done / total) * 100);
}
const htmlPercent = percent(3, 12);
  1. Open the project from the previous lesson and record its current result.
  2. Type and run the example, then complete this task: Write remaining(done,total) without returning a negative number; test valid and invalid totals.
  3. Change at least one input, predict the result, and verify it.
  4. Create and repair this lesson's typical failure: A local variable is unavailable outside the function; return the needed result.

Read the important lines

  • Turn repeated calculations into functions with clear inputs and stable returns.
  • Read the code as input, processing, and output; point to each part.
  • A first successful run is not enough; verify a different input and an edge case.

Common mistakes and what to check

SymptomWhat to check
The result differs from the predictionA local variable is unavailable outside the function; return the needed result.
Nothing changes after refreshSave the file, verify the script path, and read the first relevant Console error.

Practice without copying

Write remaining(done,total) without returning a negative number; test valid and invalid totals.

Check the answer after you try

Rebuild it without copying and explain each decision. Key check: A local variable is unavailable outside the function; return the needed result.

Completion check

  • I produced the required visible result
  • I can explain the input, processing, and output
  • I tested normal, edge, and failure cases

Your privacy choices

Necessary storage is always on. Optional analytics and support services load only after consent.