-2

I was trying to make an isNaN() function that checks the user's input if its a NaN or not, but it always skips the the first condition whatever the user's input is.

function isNaN() {
    let value = prompt("enter value");

    if (typeof value === "number") {
    console.log("value is number");
    }else {
    console.log("NaN");
    }
} isNaN();

I made the program to checks the user's input data type by typeof operator.

4
  • 2
    prompt() always returns a string or null. Even if the string looks numeric, the type is still string. Commented Aug 9, 2024 at 19:23
  • Use parseFloat() to try to convert the input to a number. It will return NaN if it can't parse it. Commented Aug 9, 2024 at 19:24
  • 2
    This would be a good time to learn to debug unexpected output. Also note that potentially overwriting the default isNaN() implementation, intentionally or not, is not a good idea. Commented Aug 9, 2024 at 19:24
  • Wouldn't it have been simple to just do console.log(typeof value) to see why the condition isn't working as expected? ericlippert.com/2014/03/05/how-to-debug-small-programs Commented Aug 9, 2024 at 19:29

1 Answer 1

0

Try this:

    let value = prompt("enter value");
    console.log("Value entered:" + value);
    console.log("Type of value: " + typeof value);

    if (!isNaN(parseFloat(value))) {
    console.log("String contains a number");
    }else {
    console.log("NaN");
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.