What is NaN in JavaScript?
In JavaScript, we have the datatype number that allows us to store numbers like integers and floating-point numbers, and once a special value included in a number is NaN. NaN is a property of a global object that means it is always present in the global scope and NaN stands for not a number. If we console log the type of in JavaScript we will see the number data type:
We can also check whether a value is NaN or not with the help of the global method isNaN():
console.log(isNaN(output)); // true
Equality check with NaN
It is quite interesting that when NaN is compared to itself, it returns false. We can see that NaN is not equal to any property in JavaScript::
What returns NaN?
Now that we know what NaN is, let us find out what operation returns NaN:
If the output of a math operation is not a real number then it returns NaN for example:
If you are converting a string to a number then NaN will be returned hence in short we can say that parsing fails when one converts a string to a number:
const myNumber = parseInt(myString);
console.log(myNumber); // NaN
In a+b, a and b are operands, and + is operator hence when you use undefined in place of an operand and performs some operation then NaN will be returned:
When you use string as an operand in any math operation it will also return NaN:
When you give invalid arguments to a math function, it will also return NaN for example:
Conclusion
NaN stands for Not a Number and is a property of a global object which means it has always a global scope. NaN is used to check a failed operation on some number, for example, parsing numbers, passing invalid arguments to a math function, the output of a math function is not a real number, using undefined as an operand, and using a string in a math operation. The isNan() built-in method gives us the ability to check for a value so that we can find out if it is NaN or not by returning a boolean value i-e true or false. In this post, we discussed what is NaN, the equality check of NaN and what returns NaN in JavaScript.