Created
August 5, 2025 04:10
-
-
Save asbp/f01494b68e6a4baedfe9b1987dce9555 to your computer and use it in GitHub Desktop.
reliable way to check if a value is a NaN or not
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isValueNaN(value) { | |
if(typeof value === "string") { | |
value = String(value).trim().length < 1 ? NaN : value; | |
} | |
// Coerce to number (same as global isNaN behavior) | |
const num = Number(value); | |
// NaN is the only value not equal to itself | |
return num !== num; | |
} | |
const test = [ | |
"", | |
" ", | |
"1.23", | |
"123ABC", | |
12, | |
NaN, | |
]; | |
for(const item of test) { | |
console.log(`Is "${item}" a NaN?: ${isValueNaN(item)}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment