0

I am trying to validate user input to see if they enter a number and show an error if they enter anything that's not a number.

here is the html element

<input type="text" id="user_input">

here is my javascript

let user_input = Number(document.querySelector("#user_input").value);

if (user_input == NaN) {
    console.log("its not a number");
} else {
    console.log("its a number");
}

Here, when I enter a string, it still says "its a number" on the console. Why is this happening?

craftdeer
  • 985
  • 5
  • 20
  • 36
  • 1
    Use [`isNaN()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN). `NaN` is a value, doing `something == NaN` you're checking the value, not the type – Cid Dec 07 '21 at 06:16
  • `NaN == NaN` is false – charlietfl Dec 07 '21 at 06:18
  • and `typeof(NaN) == 'number'`. Sometime, JS puzzles me – Cid Dec 07 '21 at 06:19
  • Why not use [``](//developer.mozilla.org/docs/Web/HTML/Element/input/number), [`.validity` and `.valueAsNumber`](//developer.mozilla.org/docs/Web/API/HTMLInputElement#properties)? – Sebastian Simon Dec 07 '21 at 06:21
  • @Cid [NaN is a set of IEEE-754 Number values](/q/2801601/4642212). This, and the `NaN !== NaN` behavior, are specified in IEEE-754, not in ECMA-262. – Sebastian Simon Dec 07 '21 at 06:22
  • @SebastianSimon I know, it's just funny that *Not a Number is a number* – Cid Dec 07 '21 at 06:23

0 Answers0