Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Alexander Graham
Alexander Graham
4,651 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
218,596 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.