Decide whether a line of input can be read as a number.
What to build
A program that reads a line, tries to convert it and reports what happened.
Requirements
- Read one line.
- Print
numberif it converts to a number. - Print
textif it does not.
Input
One line of text.
Output
One word: number or text.
Constraints
The line is not empty and has no spaces.
Example
Input:
42
Output:
number
Why it works
Number gives NaN for text it cannot read, and Number.isNaN is the reliable way to detect that value. Comparing with === NaN would never be true.
Examples
Example 1 · Input
42
Expected output
number
Example 2 · Input
hello
Expected output
text
Hints
Hint 1
prompt() always gives a string, so typeof alone cannot answer this.
Hint 2
Number(line) gives NaN when the text is not a number.
Hint 3
Number.isNaN(...) tests for NaN.
Solution
Show one correct solution (try it yourself first)
const line = prompt(); console.log(Number.isNaN(Number(line)) ? "text" : "number");