Find the responsibility
Two screens need the same order subtotal. Copying the formula works today, but both copies must change if the rule changes. What part is shared: the calculation, the screen layout or both?
A function gives a name to a reusable operation. A declaration describes the operation; a call executes it. Separate calculation from display so the result can serve different callers.
function calculateSubtotal(unitPrice, quantity) {
return unitPrice * quantity;
}
const firstSubtotal = calculateSubtotal(20, 3);
const secondSubtotal = calculateSubtotal(15, 2);
console.assert(firstSubtotal === 60);
console.assert(secondSubtotal === 30);
console.log("First subtotal:", firstSubtotal);
The names inside parentheses are parameters. Values supplied in a call are arguments. return sends a value back and ends that call. Each call has its own parameters. The calculation does not need to know which screen will use it.
Guided design comparison
A function that calculates, prints a receipt and changes global stock has several reasons to change. For our quote, a calculation with a return value is easier to verify. This does not mean every function must be one line; it should have one understandable responsibility.
Avoid inventing a generic "process anything" function simply because two lines look similar. Share behavior when its meaning and rules really belong together.
Independent exercise
Extract the rule "add one fixed packing charge to a subtotal" into a function. Call it with 60 and 5, then with 30 and 0. Predict the results and explain what must not happen outside the function.
Correction
function addPackingCharge(subtotal, packingCharge) {
return subtotal + packingCharge;
}
console.assert(addPackingCharge(60, 5) === 65);
console.assert(addPackingCharge(30, 0) === 30);
It should not change stock, send a message or decide an unrelated discount. Those actions are not required to answer this calculation. The function currently assumes valid numbers; document that limit instead of hiding it.
Review
Can you name the function as an action, explain its inputs and state its result in one sentence? If not, clarify the responsibility before adding more code.