Understanding NaN in JavaScript: What is Not-A-Number?


NaN in JavaScript (Not-A-Number)
The NaN
global property in JavaScript represents a value that is "Not-A-Number." While NaN
is classified as a number, it signifies that the value it represents is not a valid number.
What is NaN?
Definition:
NaN
stands for "Not-A-Number."Purpose: It indicates that a calculation did not yield a valid numerical result.
For instance, during a calculation, if an invalid number is generated, JavaScript represents it using NaN
.
Example: Invalid Number
let result = 0 / 0;
console.log(result); // Output: NaN
Here, dividing 0
by 0
produces an invalid result, represented by NaN
.
Key Characteristics of NaN
NaN is a Number: While
NaN
stands for "Not-A-Number," it is still categorized as a number in JavaScript.Invalid Representation:
NaN
indicates a value that cannot be represented as a valid number.
Valid Numbers
Here are examples of valid numbers:
console.log(1); // Output: 1
console.log(2); // Output: 2
console.log(2.5); // Output: 2.5
In contrast, the following is an example of an invalid number:
let invalidNumber = 0 / 0;
console.log(invalidNumber); // Output: NaN
In this case, while NaN
is technically a number, it does not represent a valid numerical value.
Operations with NaN
You can perform operations involving NaN
, but the results will also be invalid (NaN
).
Example
let invalidOperation = NaN + 5;
console.log(invalidOperation); // Output: NaN
Why?
Any operation with NaN
results in NaN
because the original value is not valid. For instance:
let invalidAddition = NaN + NaN;
console.log(invalidAddition); // Output: NaN
let invalidMultiplication = NaN * 2;
console.log(invalidMultiplication); // Output: NaN
Subscribe to my newsletter
Read articles from Anmol singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
