Today, we'll talk about the Javascript method Number.isNaN
and the global Javascript function isNaN()
.
Β
Number.isNaN()
and isNaN()
Both Number.isNaN()
and isNaN()
return a boolean
, depending on the value that has been passed.
console.log(isNaN(5)); // false
console.log(Number.isNaN(5)); //false
Β
isNaN()
Determines whether or not a value is NaN (not a number)
and returns a boolean
(true
or false
).
console.log(isNaN(8)); // prints false, as 8 is a number
console.log(isNaN('100F')); // prints true, 100F is not a number
isNaN()
however, behaves strangely when passed non-numeric arguments at times, and it is considered unreliable compared to Number.isNaN()
.
This is because isNaN()
tries to convert any non-numeric argument passed into it to a Number
, and tests the resulting value of that instead.
// these equate to true, despite them clearly not being numbers
console.log(isNaN('NaN'));
console.log(isNaN(undefined));
console.log(isNaN({}));
console.log(isNaN('blah'));
Β
Number.isNaN()
Number.isNaN()
determines whether a value passed is NaN
(Not a Number), using the type Number
.
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(6)); // false
Generally, we prefer to use Number.isNaN()
as a default, as it is more robust than isNaN
, its original.
Below is a look at the function typeOfNaN(value)
, which takes in a value
and uses if
statements to determine which type of NaN
was passed into it, we use console.log
afterwards to print out which type of NaN
was detected.
function typeOfNaN(value) { // tests which type of Not a Number was passed in as 'value'
if (Number.isNaN(value)) { // if this is true
return value + ' is not a number evaluated with Number.isNaN()';
}
if (isNaN(value)) { // tests if this is true
return value + ' is not a number evaluated with isNaN()';
}
}
console.log(typeOfNaN('100F'));
// output: "100F is not a number evaluated with isNaN()"
console.log(typeOfNaN(NaN));
// output: "NaN is not a number evaluated with Number.isNaN()"
We can also check if this value
is false
i.e. a Number
, simply by using == false
.
if(Number.isNaN(5)==false) {
console.log('This is a number!');
}
Top comments (0)