Published lesson · 30 minutes

Write reusable functions

Objective: Create a function with clear parameters and a return value for one small, repeatable task.

Understand the idea

Write reusable functions works best when the learner can explain the reason behind each step, not just copy a result. A function names a task and separates its inputs from its result; returning a value makes the result reusable by another part of the program.

A volunteer rota formats a participant name and shift time in the same way on a list and a confirmation message. Treat the names and details as invented practice information; the example is for learning a method and does not describe a live service.

A dependable sequence is: Choose a verb for the function name, pass the values it needs as parameters, return the formatted result and call it with more than one input. Write down the important decision before you begin so another person can follow the reasoning.

Check an empty or unexpected input explicitly. Avoid changing a variable outside the function when a returned value is enough. Compare the result with the objective, then change one thing at a time if the first attempt does not work.

Write two calls to the same function using different synthetic shift details. Explain one assumption that would need checking before anyone used a similar result outside the classroom.

Keep a short record of the choices you made and the evidence you used to check them. A useful practice result is understandable by another learner, stays within the stated scope and makes its limitations visible before anyone relies on it.

Worked examples

Write reusable functions: practice example

Explore how write reusable functions supports the lesson objective with a small synthetic example.

main.js

function weeklyTarget(goal, weeks) {
  if (weeks <= 0) return null;
  return Math.ceil(goal / weeks);
}
console.log(weeklyTarget(120, 6));

Practice tasks

  1. Explore write reusable functions

    Use the worked example for “Write reusable functions”. Change one small detail to suit a different synthetic community situation, then explain what you expected and how you checked whether the change still met the lesson objective.

  2. Build a JavaScript practice example

    Create a small practice result that demonstrates this objective: Create a function with clear parameters and a return value for one small, repeatable task. Use only synthetic information, keep the first version focused, and write down one limitation that a later version should address.

  3. Review and explain the result

    Review your “Write reusable functions” result as if another learner will use it without your explanation. Identify one strength, one exact point that may be unclear, and a revision that would make the result easier to understand or use.

Write reusable functions becomes easier when you choose a verb for the function name, check the result and explain the choice to another learner.

Course overview