Sometimes, it is requirement to check whether a variable is number or coerced to a number or not.
We can utilize isNaN
method available in Number
object to check it.
The isNaN
method returns true only when value is NaN
or coerces to NaN
.
Here is an example:
const var1 = 34;
if (Number.isNaN(var1)) {
console.log("NaN value");
} else {
console.log("Not a NaN value");
}
This will print the following
Not a NaN value
Here is second example:
const var2 = "hello world";
if (Number.isNaN(var2)) {
console.log("NaN value");
} else {
console.log("Not a NaN value");
}
This will print the following:
NaN value
here Number.isNaN(var2)
coerces to NaN
value.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.