Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Alexander Graham
Alexander Graham
7,966 Points

Confusion with the isNan() function

I'm confused with how isNan() function works... it's suposed to return 'true' if what's inside is NOT a number, for example: isNan('ten'), this will return 'true'. However if I type isNan('10') it will then return 'false' considering it as a number, but we all know that '10' is not a number (you can see this by writing "typeof '10' " and it will return a string).... so why is this?

1 Answer

Steven Parker
Steven Parker
229,670 Points

It looks like there's two issues contributing the confusion. One is type coercion, which is when the system converts a value's type (if possible) to fit the way it is being used. For example, a string containing digits will be converted into a number when passed to a function expecting a numeric argument or if math is performed on it. So isNan('10') is false and '10' * 3 is 30.

Another issue is that isNan() doesn't check type type of the value, if you wanted that you could do typeof x != "number". Instead, it checks for a special numeric value known as "NaN", which is commonly the result of attempting to convert a non-digit string into a number or attempting math on non-numbers that cannot be coerced. For examples: parseInt("word") or "word" * 2. The isNaN() function is needed because NaN has the unusual property of not being equal to itself. So NaN == NaN is false. For more details see this MDN page on NaN.