Functions and input contracts
A function groups reusable work. In backend code, small functions are useful when they accept explicit inputs and return a result instead of relying on hidden state. An input contract states which values the function accepts and what the caller can expect.
Local practice: The proposed teaching runtime is Node.js 26.13.1 LTS. These original offline examples were executed on Node.js 22.16.0 (Linux x64); execution on the proposed baseline and in ByteMind is not yet verified. No npm dependencies are required. Use a fresh practice directory. Code blocks are static, not a browser-based Node runner.
Return an order total
function totalCents(quantity, unitPriceCents) { return quantity * unitPriceCents;}console.log(totalCents(2, 650));console.log(totalCents(0, 650));In the directory containing the files above, run:
node main.mjsExpected standard output:
13000Expected exit status: 0.
How it works
A function declaration names parameters. Each call supplies argument values, and return passes a result back to the caller. A pure function returns the same result for the same inputs and does not change external state. These calculations are pure; the surrounding console output is a separate side effect. For this lesson assume nonnegative integer quantities and prices in cents, with products small enough to be represented exactly as JavaScript numbers. Later lessons validate external input before calling such a function.
Separate calculation from display
function remainingCents(budgetCents, costCents) { return budgetCents - costCents;}const remaining = remainingCents(2000, 850);console.log(remaining);In the directory containing the files above, run:
node main.mjsExpected standard output:
1150Expected exit status: 0.
Common mistake
Printing inside a function is not the same as returning a value. If a function only logs a number and has no return statement, the caller receives undefined. Keep domain calculations separate from logging to make them easier to test and reuse.
Try it yourself
Write lineTotal(quantity, priceCents) and return the product. Test 3 and 250, then 0 and 250. Add a second function that subtracts a known cost from a budget. Keep all units in cents.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions and input contracts — knowledge check
Check your understanding of functions and input contracts.
What does `return` do in these functions?
What is totalCents(0, 650)?
Why keep logging outside a calculation?