Build with AI: From Zero to Your First App · Module 5: Turn a page into an app · Lab
Price Calculator With Guards
35 min hands-on · Core
Browser only. The unguarded calculator below is provided as starter material; save, open, break it, then guard it.
Three ways to do this lab. A: the browser steps below, the main path, free with no account. B: try the same task with your own AI tool if you have one (its terms and quotas apply). C: work from the provided material and the worked solution below, which teaches the same skill. No path claims you used a live AI tool when you did not.
Objectives
- Reproduce NaN and blank-echo failures on an unguarded calculator
- Add trim, empty and conversion guards before any math
- Show an echo line with entered values plus the total
Step 1
Break it first
Save the starter file, open it, submit empty, spaces-only and letters-in-quantity. Record the three broken outputs (NaN total, blank echo or similar).
calc.htmlhtml FORM (unguarded starter) Fields: qty (quantity), out (result line). Behavior: total = qty * 2; echo shows qty. No trim, no empty check, no conversion check.Step 2
Guard it
Add guards in order: trim the input, refuse empty with 'how many loaves?', convert to number, refuse non-finite with 'that does not look like a number'. Only then compute and echo.
Step 3
Verify three cases
Submit empty, spaces-only and a real value. Record each output line. All three must read as sentences, never NaN or blank.
How to confirm it worked
- Three broken outputs recorded before the fix
- Guards run in trim, empty, convert, finite order
- Echo plus total shown for the real value
- No NaN, undefined or blank output in any case
Try it here
0/4 checks passing · Coverage only, not a quality score.
The starter project is loaded below. Edit, preview with Run, then run the behaviour checks. No account needed; your draft stays in this browser.
Up to 10 files, .html/.css/.js only, 100 KB each. A failed import never touches your draft.
Draft kept in this browser.
Hints, in three stages
Stage 1: a nudge
Break it on purpose first. The recorded failures are the test suite your guards must pass.
Stage 2: a direction
Empty quantity is missing, not zero. Never default it silently; ask instead.
Stage 3: almost the answer
The echo line is the proof of reading. Total without echo means the math may be right and the understanding wrong.
Worked solution (open after an honest attempt)
Worked solution. Guards: value.trim(); if empty show 'how many loaves?'; const n = Number(value); if not finite show 'that does not look like a number'. Then echo '2 loaves' plus total '4 USD'. Empty, spaces and letters each get a sentence; the real value gets echo plus total.