0

According to this code

function sayHi(myAge) {
    "use strict";
    if (isNaN(myAge)) {
        return "Ture";
    } else {
        return "False";
    }
}
sayHi("12");

isNan() return false, Why? "12" is not a number.

Because When I do this

var myAge = "12";
alert(myAge === 12);

it will return false, because "12" is a string but 12 a number.

MMJ
  • 279
  • 7
  • 23
  • What does `alert(myAge == 12)` return? "12" is converted into a number. When you check with === it is strict equality. – Dominique Lorre Sep 14 '16 at 16:26
  • 1
    Are you trying to validate numbers? Maybe you're looking for something like: http://stackoverflow.com/a/9716488/63011 – Paolo Moretti Sep 14 '16 at 16:28
  • @DominiqueLorre return `true` , That's what I am looking for, I am just want to figure out why isNan() return `false` for `"12"` – MMJ Sep 14 '16 at 16:34
  • 1
    NaN is a special value, which means "undefined" or "not possible to display". Check [this](https://en.wikipedia.org/wiki/NaN) – Dominique Lorre Sep 14 '16 at 16:40

3 Answers3

2

From the spec:

Returns true if the argument coerces to NaN, and otherwise returns false.

Compare to ===:

If Type(x) is different from Type(y), return false.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Because NaN is a special value in JS, not a type. sayHi(NaN) will return true.

If you want to check if the value is the Number type, you should do

if (typeof myAge === "number")

And if you want to be sure, that it's not NaN as well, then

if (typeof myAge === "number" && !isNaN(myAge))
Alexey Katayev
  • 248
  • 2
  • 10
1

The isNaN() function determines whether a value is NaN or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use Number.isNaN(), as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.

Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

Liberateur
  • 1,337
  • 1
  • 14
  • 33