Hello readers, We have covered five questions from my front-end interview questions series until now, and today we are going to discuss the 6th question of the series.
What is NaN
NaN
stands for Not-a-Number, In JavaScript it represents a value that is not valid number. It is a global value meaning it is accessible from anywhere in our code.
How NaN is created?
Let’s see some examples that returns NaN
.
Dividing zero by zero
console.log(0 / 0);
Taking the square root of a negative number
console.log(Math.sqrt(-2)); // NaN
Trying to convert non-numeric values to numbers (e.g., “hello” to a number)
console.log(parseInt("hello")); // NaN
Performing arithmetic operations with infinity
console.log(0 * Infinity); // NaN
console.log(1 ** Infinity); // NaN
console.log(Infinity / Infinity); // NaN
console.log(Infinity - Infinity); // NaN
Other arithmetic operations
console.log("hello" - 2); // NaN
console.log("hello" * 2); // NaN
console.log("hello" / 2); // NaN
Characteristics of NaN
When we compare NaN
to NaN
it returns false
π
console.log(NaN === NaN); // false
console.log(NaN == NaN); // false
console.log(NaN !== NaN); // true
console.log(NaN != NaN); // true
Checking for NaN
We use isNaN
function to check if the provided value is non-numeric
console.log(isNaN("Hello")); // true
console.log(isNaN(NaN)); // true
console.log(isNaN(12)); // false
console.log(isNaN("12")); // false
For more precise checks, we use Number.isNaN()
. It was introduced in ES6.
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(12)); // false
console.log(Number.isNaN("12")); // false
Number.isNaN()
returs false
for all values except NaN
.
isNaN()
convert the provided value to number
before checking if it is NaN
, on the other hand Number.isNaN()
does not perform any type conversion. It strictly checks if the provided value is NaN
without trying to convert it.
If you find this helpful please share with your network β .
Happy Coding π !