JavaScript - Check if a variable is a number : typeof doesnt work, isNaN does
javascript, numbers, typeof
Solution
The `isNaN()` function implicitly coerces its argument to be a number. If you pass it the string "12", it returns `false`. Thus in your code the value of the variable could be a string representation of a number, and it'll make it through the tests if it's a "nice" string.
The concept of `NaN` does not really mean, generally, "not a number". It's not really about data types. It's a feature of the IEEE floating point format. There are bit patterns that are "not numbers", and the pseudo-value `NaN` represents those. It happens that the language designers decided to have failed numeric conversions result in `NaN` as a sort of marker.
In newer JavaScript environments, there's another `isNaN` function on the `Number` constructor. It differs from the global `isNaN()` in that it performs no type coercion at all, and it only checks to see if its argument is `NaN`. If you pass it a string — even a string like "banana", which isn't anything like a number — it returns `false`, because no string value can be the number `NaN`.
Problem
I currently face a problem, it may be very simple but I found nothing in my research... I want to check (in JavaScript) that a variable is a number, and if it is higher than 100 or lower than 0. I tried this : ``` if ((returnValue > 100) || (returnValue < 0) || (typeof returnValue != 'number')) { //not correct } else { // let's do some stuff here } ``` But it doesn't work... When I put for example the number 50 (which is good), happening in the "if" and not in the "else" as expected ! So I did : ``` if ((returnValue > 100) || (returnValue < 0) || (isNaN(returnValue))) ``` and then I noticed that it perfectly worked ! I know too I could split that in two parts , firstly testing if the variable is a number and then if it is greater than 100 or less than 0, but this is not what I am currently looking for ;) Could you please explain me why the first try doesn't work (and/or make it work) ? Thanks !