What Is "NaN"
SemihGKL
Posted on December 29, 2022
So what is NaN ??
spoil : It's a Number
Table of contents
- NaN beginners introduction
- My tips to verify number
- My second tips to verify the opposite
1 - What we need to know about that ? Basically... 3 things for beginners
1 - NaN is the result of an arithmetic operation that was invalid.
2 - For many of us NaN == Not A Number, but for sure, it has a 'number' type.
3 - We can not compare NaN to itself.
To illustrate all these things I will show you some examples :
- #1
const whatIsNaN = 1 / "a"
console.log("#1 - You can have "NaN" like that : 1 / a = " + whatIsNaN);
- #2
console.log("#2 - The type of NaN is : "+typeof NaN);
- #3
if (NaN === NaN) {
console.log("We never catch this log");
} else {
console.log("But always this log");
}
//If you need to catch a NaN, you can use that :
if (Number.isNaN(NaN)) {
console.log("I'm a NaN !");
}
2 - My tips
In my experience, the method that I prefer to use to check if a variable is a "number" :
//The regex to match with numbers.
const nbRegex = /^-?[0-9]\d*(\.\d+)?$/
/*
Here you can see how many elements in your array
do not match with the regex that we defined.
Here "args" is an array
*/
function isNotNumber(args) {
return args.filter(arg => !arg.match(nbRegex)).length;
}
So, with this function if the return is more than 0 ?
It's the proof that the array you passed as an argument contains some stuff that is not a number :
//Here "args" is an array
if (isNotNumber(args) > 0) {
console.log("This array does not contain number only.");
return
}
3 - My second tips to verify the opposite
In an other way you can just delete the "!" in the filter function to have the perfect oposite and only stuff that is not numbers :
//Here "args" is an array
function isNotNumber(args) {
return args.filter(arg => arg.match(nbRegex)).length;
}
To test that :
//Here "args" is an array
if (isNotNumber(args) > 0) {
console.log("This array does contain some number.");
return
}
Posted on December 29, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.