Build a Small JavaScript Receipt Calculator
Quick answer
A small calculator is a useful first project because its inputs and outputs are easy to check. Here a fixed price and delivery charge define a simple business rule. The only input is a nonnegative whole-number quantity.
How it works
Separate the calculation from display. A function can return quantity * price + delivery, while the caller chooses whether to display or test that result. All values in this demonstration are small integer currency units. Fractional prices, validation and realistic tax rules are later topics. The stated rule charges delivery even at quantity zero.
function receipt(quantity) { const price = 8; const delivery = 3; return quantity * price + delivery;}console.log(receipt(4));console.log(receipt(0));Expected console output (Node.js):
353Four items cost 32 plus delivery; zero items still incur the specified charge.
function receipt(quantity) { const price = 8; const delivery = 3; return quantity * price + delivery;}const first = receipt(1);const second = receipt(2);console.log(first + second);Expected console output (Node.js):
30Two separate orders cost 11 and 19 because each has its own delivery charge.
Common mistakes
Do not hardcode a result that works for just one quantity. The function must use its parameter. This demonstration assumes valid inputs rather than silently claiming that all invalid values are handled.
Practice
Build the exercise version with a different unit price and delivery rule, then manually check zero and two nonzero quantities.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Build a Small JavaScript Receipt Calculator — Knowledge Check
Review the concept and apply it to a new example.
For price 8 and delivery 3, what does receipt(2) return?
Under the stated rule, what does receipt(0) return?
Which expression adds a single delivery charge?
Why should a receipt function return a value instead of only logging it?
A solution returns 35 for every input. Which test exposes the defect?