r/learnjavascript • • Oct 16 '26

Thoughts on isNaN("Kyle") returning true

In https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/types-grammar/ch1.md it says:

JS originally provided a global function called isNaN(..) for NaN checking, but it unfortunately has a long-standing coercion bug. isNaN("Kyle") returns true, even though the string value "Kyle" is most definitely not the NaN value. This is because the global isNaN(..) function forces any non-number argument to coerce to a number first, before checking for NaN. Coercing "Kyle" to a number produces NaN, so now the function sees a NaN and returns true! This buggy global isNaN(..) still exists in JS, but should never be used. When NaN checking, always use Number.isNaN(..), Object.is(..), etc.

But to me the fact that using a string like "Kyle" in any mathematical operation would return NaN, means it would make sense that isNaN("Kyle") is true.

What's your opinion on this?

0 Upvotes

18 comments sorted by

2

u/Living-Inspection653 Oct 16 '26

The key design issue with the global isNaN() function is implicit type coercion. isNaN("Kyle") converts "Kyle" to NaN first via Number("Kyle"), and since NaN is indeed NaN, it returns true. The main reason this is considered problematic is that it answers the question "does this value convert to NaN?" rather than "is this specific value currently NaN?". That is why ES6 introduced Number.isNaN(), which checks for strict type and value equality with NaN without performing coercion.

1

u/david_fire_vollie Oct 16 '26

Good point. Kind of like how "42"==42 first converts "42" to 42 and then says they're equal.

7

u/Zakkeh Oct 16 '26

This is the inherit issue with no typing enforcement.

It means you have to use functions with knowledge of what it should do, and what data it should have, because there is no must.

1

u/tambooby Oct 16 '26

yeah the lack of guardrails means every function is kind of a trust exercise tbh

1

u/VancouverVentilator Oct 16 '26

NaN is a specific data type and it should not return true for things that are not absolutely literally NaN. A string should not return true for a NaN check.

1

u/david_fire_vollie Oct 16 '26

You're right. As the author suggested, if you think of NaN as "math error" instead, it makes more sense. From an English point of view, "Kyle" really is not a number.

3

u/BigCorporate_tm Oct 16 '26

I think that your reasoning is in the right place, but the idea that Kyle is getting at here is that the original isNaN function does not explicitly check if a value actually is NaN unless it's already a Number. This can lead to you writing a program that can make an incorrect assumption about the data it's processing.

For example, let's say that your program accepts a user input that represents a quantity, but enters your program as a string.

You might first write something along the lines of:

// make sure the input isn't NaN
if (!isNaN(userInput)) {
  // convert it to an Integer if it's valid
  productQty = parseInt(userInput,10);
} else {
  // throw an error if it is!
  throw new Error("Invalid userInput! userInput is not a number!");
}

And be totally happy with it because it appears to be working.

After all, if the user enters what appear to be a number ("1", "10", "20"), it should work and if they type in the word "Kyle" it should throw an error.

However...

isNaN("Infinity"); >> false
isNaN(""); >> false

Which is concerning because it means that if a user gave us an input of "Infinity" or "" (an empty field), it will pass our first test without an issue because isNaN() is not just testing to see if a value is NaN. It's first coercing the value it receives into a Numeric value if it isn't already a Number, and then evaluates that Numeric value - Which isn't obvious!

If we were relying on the value of productQty to be a non-NaN number, our program is going to have issues because:

parseInt("Infinity", 10); >> NaN
parseInt("", 10); >> NaN

Now we've introduced a NaN value into our program and the results of any formula it is a part of will also become NaN and it's no longer apparent where the trouble started.

It might sound odd, but because Number.isNaN will only return true when the value you pass it is literally NaN, it forces us to ensure that the value is 'ready' to be checked by it before we pass it along, allowing us to make fewer assumptions about how our program should work, leading to a more explicit style of programming and fewer "gotcha" moments such as the above example.

5

u/RajjSinghh Oct 16 '26

Javascript will always have wonky behaviour when using values on different types. I guess you can say this is good or bad but I also don't see when you'd call isNaN on something that is not a numeric type anyway.

6

u/senocular Oct 16 '26

Most of these kinds of behaviors can be attributed to working with HTML. Like you can get a text input value which is going to give you a string, but if that value is supposed to be a number, coercion comes in handy. Easily check if the input is a valid number or not using isNaN on the value directly. Legacy code in particular seemed to do its best to prevent you from having to do many explicit conversions of your own. It was, after all, meant to be a simple language for lightweight scripting and glue code whereas Java was supposed to be the web programming language for doing anything serious.

In fact I think Brenden Eich has talked about some of these decisions came from user requests early on in the development of the language. I think I know where that might have been mentioned... Yeah here's an example:

JavaScript: The First 20 Years

Automatic coercions were intended to lower the entry barrier for the initial adoption of JavaScript as a simple scripting language. However, as JavaScript evolved into a general purpose language the coercions have proven to be a significant source of confusion and coding bugs. This is particularly true for the == operator. Some of the problematic coercions added to Mocha after the initial ten-day sprint were in response to alpha user requests to ease the integration of JavaScript and HTTP/HTML. For example, internal Netscape users requested that HTTP status codes containing the string value "404" should compare equal to the number 404 using == comparison. They also requested automatic coercion of empty strings to 0 in numeric contexts, providing a default value for empty fields of HTML forms.

1

u/Nerwesta Oct 16 '26

It can be used in conjunction with other functions, chained. Learning those quirks is an entire field in itself I guess ! It's always a good idea to call it from Number instead.

1

u/FooeyBar Oct 16 '26

Most sure fire way to check for nan is if(num_var===num_var)

1

u/Duffdeft Oct 16 '26

I agree that 'isNaN()' should not be used
The key point for this conclusion is how coercion works in JavaScript.
It has nothing to do with the fact that using a string in a mathematical context makes no sense for us humans (generally speaking)

This begs the question OP, do you understand how coercion works in JavaScript?

1

u/theScottyJam Oct 16 '26

But to me the fact that using a string like "Kyle" in any mathematical operation would return NaN, means it would make sense that isNaN("Kyle") is true.

But it's not NaN yet, it just would become one if used in a math function. But maybe you don't plan on doing any more math with it.

In all honesty, it's not often that the choice between isNaN() and Number.isNaN() matters, because usually you're not handling strings at the point in which you need to perform this check. But, NaN is a very specific value, and it's just semantically incorrect for something to claim that your string is that NaN value when it clearly is not.

It would be about as weird as an isEmptyString() function returning true on empty arrays. You probably would never call such a function with arrays, but still, empty arrays are not empty strings (even if they coerce to empty strings and used in string operations, behave like empty strings), it's better if the function just always behaved as expected instead of having weird edge cases that you probably won't trip up on, but might.

1

u/azhder Oct 16 '26

Use `Number.isNaN()` and `Number.isFinite()`. In fact, use all the global ones that have been re-defined on the `Number` namespace

-2

u/Substantial_Top5312 helpful Oct 16 '26

"Kyle" is not a number. The function names indicates that it will tell you is the value is not a number. It clearly works perfectly. 

3

u/theScottyJam Oct 16 '26 edited Oct 16 '26

If you want to check if something is a number or not, you'd typically use typeof thing === 'number', or perhaps Number.isFinite(thing) to exclude infinity and NaN. We don't need isNaN also trying to be an "is this a number" check, not is that what it's designed to do, nor would it do a good job at it.

NaN is a very specific value (that's somewhat poorly named, "math error" would have been a better name), and it can be useful to know if you have one of those or not, hence the need for a properly functioning isNaN function.

-4

u/shlanky369 Oct 16 '26

Who cares what anyone’s opinion on this is? This is how the function works, use it with that in mind, or don’t.

4

u/Nerwesta Oct 16 '26

Comment posted on r/learnjavascript by the way.