Is there any way to detect - or safely guard against - NaN
values during runtime, across any part of the application where these might appear?
- A) Is there a safe linting to warn about potential
NaN
values that might occur in certain constructs? - B) Alternatively, some kind of solution that monitors the executed JavaScript during runtime, detects and logs or alerts about it? - Similar to how error detection services work?
Example
Pseudo-code of a scenario where testing for NaN
might be hard:
function undetectedNaN (): AssumeStrictDataTypes {
// 1. Some algorithm ...
// 2. NaN appears undetected ...
// 3. Some algorithm ...
// 4. Return: Broken but seeming legit value and data type
}
(Assume that it's in a larger application codebase, where adding checks for isNaN()
and validating individual values is not an option: It might be too costly, not a requirement, no automated testing possible etc. ...)
UPDATE 2021/12: To complement my rather abstract question: In a more practical use case, API values did not exist in an array structure. Most occurrences of NaN
could be solved by better value/type checking.
function example (a, b) {
return a[0] + b[0]
}
// undefined + undefined = NaN
const result = example([], []);
console.log(result);
Some other possibilities of NaN
occuring:
const testArray = [];
const testObject = {};
testArray[0] + testArray[0] // NaN
testObject.X + testObject.X // NaN
undefined + undefined // NaN
NaN + NaN // NaN
Other places where NaN
might be harder to track:
e.g. if it appears during runtime, somewhere, sometimes, and is not a testable return value.
// Bitwise operators
~(NaN) // -1
// Conditionals
if (NaN > 1) {} // false
// Typecasting
!!NaN // false