Full-Stack course / JavaScript fundamentals
Form field to number
How to fetch and submit this exercise
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach exercise: download it, edit the file named in the instructions, then submit.
gonomicon fetch fs-week-2/01-03-form-field-to-number
cd 01-03-form-field-to-number
gonomicon submitForm field to number
Goal: take the text from a form field, turn it into a number, and say whether it was a usable number at all.
Worked example
Text typed into a form always arrives as a string. The file starts with a box called raw holding that text. The tests swap in other text, run your code, and read two boxes you create: usable and amount.
raw | usable | amount |
|---|---|---|
"42" | true | 42 |
"3.5" | true | 3.5 |
"0" | true | 0 |
"abc" | false | null |
"12px" | false | null |
"" | false | null |
Rules
- Keep the line
let raw = "...";at the top of the file. The tests replace the text on it. usablemust be exactlytrueorfalse.- When
usableistrue,amountis the converted number (the number type, not text). Whenusableisfalse,amountisnull. - Use the built-in
Number(...)converter to decide what counts as a number. One exception: an empty field is never usable. - Compare with
===and!==, never==. Don't usevar. usablecan be aconst.amountmay need to be aletif you fill it in later.- Text with spaces in it is not part of the tests.
- To look at your boxes while you work, add
console.log(usable, amount);at the bottom and runnode form_field_to_number.js.
What you'll practice
- Converting text to a number on purpose
- Spotting a value that converts "successfully" but still isn't an answer
- Making a choice with
if
Run it
gonomicon fetch fs-week-2/01-03-form-field-to-number
cd 01-03-form-field-to-number
gonomicon test
gonomicon submit
Hints
- Add
console.log(Number(raw));and try "42", "abc" and "". Which of those answers would a person filling in a form be happy with? - The empty string turns into a perfectly normal-looking number, so the converted value alone can't tell you the field was empty. Look at
rawas well as the converted value. usableis true whenrawis not the empty string and the converted number is not NaN. Then keepamountas null unlessusableis true.