DEV Community

Cover image for What Is "NaN"
SemihGKL
SemihGKL

Posted on • Updated on

What Is "NaN"

So what is NaN ??

spoil : It's a Number

Table of contents

  1. NaN beginners introduction
  2. My tips to verify number
  3. 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);
Enter fullscreen mode Exit fullscreen mode
  • #2
    console.log("#2 - The type of NaN is : "+typeof NaN);
Enter fullscreen mode Exit fullscreen mode
  • #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 !");
    }
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

To test that :

//Here "args" is an array
if (isNotNumber(args) > 0) {
    console.log("This array does contain some number.");
    return
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)