Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check existence of NaN keyword in an array JavaScript
We have an array of elements that contains both truthy and falsy values. Our job is to write a function that returns an array with indices of those elements which are NaN in the original array.
NaN !== NaN
The datatype of NaN is actually number. Although NaN is a falsy value, it has a peculiar property that no other datatype or variable has. It's that the expression NaN === NaN yields false. And it's only in the case of NaN that this is false.
So, we can use this behavior to our advantage and pick out NaN value indices. The code for this will be:
const arr = [7, 1, "123abc", undefined, NaN, 78, NaN, null, "aes", NaN, '', null, NaN];
const pickNaN = (arr) => {
return arr.reduce((acc, val, ind) => {
if(val !== val){
acc.push(ind);
};
return acc;
}, []);
};
console.log(pickNaN(arr));
[ 4, 6, 9, 12 ]
Using isNaN() vs Number.isNaN()
The isNaN() function returns true or false based on whether the value provided is a NaN or can be coerced to a NaN. Whereas the Number.isNaN() function only returns true if the value provided is actually NaN.
So, Number.isNaN() is a more reliable way of checking for NaN over isNaN(). The difference in the code outputs is illustrated below.
Example: Comparing Both Methods
const arr = [7, 1, "abc", undefined, NaN, 78, NaN, null, "aes", NaN, '', null, NaN];
const pickNaN = (arr) => {
return arr.reduce((acc, val, ind) => {
if(Number.isNaN(val)){
acc.reliableWay.push(ind);
};
if(isNaN(val)){
acc.unreliableWay.push(ind);
}
return acc;
}, {
reliableWay: [],
unreliableWay: []
});
};
console.log(pickNaN(arr));
{
reliableWay: [ 4, 6, 9, 12 ],
unreliableWay: [ 2, 3, 4, 6, 8, 9, 12 ]
}
We can clearly see how isNaN() incorrectly identifies many non-NaN values as NaN. That's why Number.isNaN() is a more reliable way.
Comparison of Methods
| Method | Behavior | Reliability |
|---|---|---|
val !== val |
Uses NaN's unique self-inequality | Reliable |
Number.isNaN() |
Checks if value is exactly NaN | Most reliable |
isNaN() |
Coerces values and then checks | Unreliable |
Conclusion
Use Number.isNaN() as the most reliable method to detect NaN values in arrays. Avoid the legacy isNaN() function as it produces false positives through type coercion.
