Functions make a useful promise: given some inputs, perform a named task and return a result. Learn to distinguish that result from console output and to keep temporary values inside the function.
Give the function one clear responsibility
A parameter is a local name for an input; an argument is the actual value supplied by the caller. Prefer a function such as totalPrice(unitPrice, quantity) over one function that also reads the page, changes a database and displays a message. A smaller responsibility makes the behaviour easier to test and reuse.
Return and display are different actions
Returning passes a value back to the caller. Logging displays information for a developer. A function that only calls console.log does not automatically return the printed value. Decide what the caller needs and return that result explicitly. Keep display formatting at the edge when other code still needs a numeric value.
Keep temporary state local
Variables declared inside a function are available according to JavaScript scope rules. Use const when the binding will not be reassigned and let when reassignment is necessary. Avoid relying on a changing outer variable for a calculation that could receive that value as a parameter. Explicit inputs make surprising dependencies easier to spot.
Worked example
The function below multiplies a unit price by a quantity and returns 24. Its temporary result does not leak into the surrounding code. Change one argument and predict the output before running it.
function totalPrice(unitPrice, quantity) {
const result = unitPrice * quantity;
return result;
}
console.log(totalPrice(8, 3));
Expected output
24Check your understanding
Try each question before opening its explanation. These are free practice prompts; they do not use game chances.
Is a parameter the same as an argument?
They describe different sides of a call. quantity is a parameter in the function definition; 3 is an argument when the function is called with that value.
Why can a logged result still be undefined to the caller?
Logging is a side effect. If execution reaches the end of a function without a return value, JavaScript returns undefined, regardless of what appeared in the console.
What should totalPrice(8, 0) return?
It should return 0 because zero items have zero total price in this simple model. A useful test also checks whether the application rejects negative quantities before calling the calculation.
Sources and further reading
These original examples explain foundational concepts. Use the official references for complete, current details and version-specific behaviour.
About this guide: AI-assisted educational content with original examples and linked primary references. Found an issue? Tell us what to improve.