LEARN BY BUILDING
JavaScript Basics: Build and Test a Price Calculator
JavaScript adds behaviour to a page: read input, calculate a result and update the interface. Keep the calculation separate from the DOM so you can test it directly. A useful first exercise is a service estimate with explicit numeric limits and rounding rules.
STEP 1
Run a complete browser example
Save the example as index.html and open it in a browser. Enter the number of hours and submit the form. The rate is fixed at USD 25 per hour for this exercise. The result is an illustrative estimate; accepting orders or enforcing business pricing needs server validation.
- Two hours should produce USD 50.00.
- Half an hour should produce USD 12.50.
- Empty or negative input must not produce an accepted estimate.
STEP 2
Understand validation and rendering
Browser constraints help users enter acceptable values. The calculation function also checks that its input is finite and within the supported range, because JavaScript can be called without using the form. The output uses textContent, so the interface inserts text rather than interpreting markup.
- Reject Infinity and NaN.
- Define the rounding rule for money.
- Show a readable error and let the user correct the input.
STEP 3
Extend the calculation carefully
Before adding discounts or taxes, write examples with expected totals. Decide whether rounding happens per line or at the final total. Use the service quote and invoice builds to compare those decisions. Keep production prices and order acceptance on the server if a customer can rely on the result.
- Test boundary values and fractional quantities.
- Avoid repeating calculation logic in several click handlers.
- Keep user text out of raw HTML insertion.
Complete runnable example
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Service estimate exercise</title>
<form id="estimate">
<label>Hours <input id="hours" type="number" min="0" max="1000" step="0.25" required></label>
<button>Calculate estimate</button>
</form>
<p id="result" role="status"></p>
<script>
function totalCents(hours) {
if (!Number.isFinite(hours) || hours < 0 || hours > 1000) {
throw new Error("Enter hours from 0 to 1,000.");
}
return Math.round(hours * 2500);
}
document.getElementById("estimate").addEventListener("submit", event => {
event.preventDefault();
const result = document.getElementById("result");
try {
const cents = totalCents(document.getElementById("hours").valueAsNumber);
result.textContent = "Illustrative estimate: USD " + (cents / 100).toFixed(2);
} catch (error) { result.textContent = error.message; }
});
</script>
</html>Use AI with a clear specification
Adapt the bracketed details to your project. Ask your coding assistant to explain its changes, then run the examples and checks yourself.
Review this calculator. Separate pure logic from DOM rendering, validate finite numeric inputs and state the rounding policy. Add tests with expected values before adding features. Render text safely and explain the limits of browser-only validation.
Official reference
MDN: dynamic scripting with JavaScript ↗BUILD IT WITH HOW2CODE
Need this adapted to your business?
Tell us about your workflow, existing tools and expected result. We’ll review the brief and discuss the scope with you.
Discuss this project →