An Interest In:
Web News this Week
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
What is NaN in JavaScript? What is its type? How can you reliably test if a value is equal to NaN?
In JavaScript, NaN
is a property of the global Object
. In other words, it is a variable available in the Global scope.
It stands for Not-A-Number but interestingly, its type is number
.
console.log(typeOf NaN); // "number"
It is used to denote an object that is not or does not compute to a number
, in a context when number
operations are applied on that object.
Another interesting fact about NaN
is, it never equals to itself. So NaN == NaN
or NaN === NaN
is always false
.
console.log(NaN == NaN); // falseconsole.log(NaN === NaN); // false
Testing for NaN
Since a NaN
is never equal to another NaN
, a self-comparison of a value makes it the most reliable way to test if the value is NaN
.
function isThisNaN(value) { return v !== v };isThisNaN(1); // falseisThisNaN(NaN); // trueisThisNaN(Number.NaN); // trueisThisNaN('NaN'); // false
Other ways to test if an object is NaN
are using the isNaN()
global method and Number.isNaN()
.
console.log(isNaN('hi')); //trueconsole.log(isNaN('4'); // false
In the two examples above, isNaN()
waits for type coercion on the string
before it makes the comparison. In the first case with 'hi'
, the string
is coerced to number
, which then evaluates to NaN
because it doesn't return a number. In the second case with '4'
, it gets evaluated to a number
so it is not a NaN
. So using isNaN()
is not very reliable to test for NaN
In contrast, Number.isNaN()
tests the current value:
console.log(Number.isNaN('hi')); // falseconsole.log(Number.isNaN('4')); // false (this time because // it's a string in the // context of a Number method)
Type coercion is not present with Number.isNaN()
. Instead, it compares the string directly. In the code above, both 'hi'
and '4'
are string
s and therefore not NaN
in the context of a Number
method. This makes Number.isNaN()
more reliable than isNaN()
while testing for NaN
values.
References
Original Link: https://dev.to/anewman15/what-is-nan-what-is-its-type-how-can-you-reliably-test-if-a-value-is-equal-to-nan-4bp3
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To