Short Description: Learn the key differences between isNaN()
and Number.isNaN()
in JavaScript. Understand type coercion, pitfalls, and best practices for handling NaN
.
Keywords: JavaScript isNaN()
, Number.isNaN()
, type coercion, NaN handling, JavaScript numbers, ES6
π Introduction
In JavaScript, handling NaN
(Not-a-Number) values is a common source of confusion.
We have two different methods for checking NaN
:
-
isNaN()
β the older, global function. -
Number.isNaN()
β introduced in ES6 to fixisNaN()
quirks.
Letβs break them down with examples and comparisons π
π What is isNaN()
?
The isNaN()
function checks whether a value is NaN
. But before doing so, it tries to convert the value into a number.
β
Syntax:
isNaN(value)
β Behavior:
-
true
β if the converted value isNaN
. -
false
β if the converted value is a valid number.
π Example:
isNaN("2"); // false β "2" β 2
isNaN("abc"); // true β cannot convert β NaN
π What is Number.isNaN()
?
The Number.isNaN()
method was introduced in ES6. Unlike isNaN()
, it does not coerce values.
β
Syntax:
Number.isNaN(value)
β Behavior:
- Returns
true
only if the value is literally NaN. - No type conversion happens.
π Example:
Number.isNaN("2"); // false β it's a string
Number.isNaN("abc"); // false β still a string
Number.isNaN(NaN); // true β exactly NaN
βοΈ Comparison: isNaN()
vs Number.isNaN()
Value | isNaN(value) |
Number.isNaN(value) |
Why? |
---|---|---|---|
NaN |
β true | β true | Both detect actual NaN |
"123" |
β false | β false | String β number works |
"ABC" |
β true | β false | Global isNaN coerces, Number.isNaN does not |
undefined |
β true | β false |
undefined β NaN via coercion |
null |
β false | β false |
null β 0 when coerced |
{} |
β true | β false | Object β NaN in coercion |
[] |
β false | β false | Empty array β 0 |
true |
β false | β false | true β 1 |
π Examples Side by Side
// Classic isNaN()
isNaN("Hello"); // true β coerced into NaN
isNaN(undefined); // true β coerced into NaN
// Modern Number.isNaN()
Number.isNaN("Hello"); // false β it's a string
Number.isNaN(undefined); // false β it's undefined
Number.isNaN(NaN); // true β only works for NaN
π― Key Takeaways
-
isNaN()
β coerces values before checking β can give unexpected results. -
Number.isNaN()
β strict check β only returns true for realNaN
. - β
Best Practice: Always prefer
Number.isNaN()
in modern JavaScript for reliability.
βοΈ Written by Yogesh Bamanier
π Connect with me on LinkedIn
Top comments (1)
Verry well explained!ππ»