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

Nermin Kekic
Nermin Kekic
6,971 Points

isNaN("2") returns false, why?

Hello friends, Today i learned about this javascript function isNaN(arg) that returns true if the argument is a string and it returns false if the argument is a number.

So i went into console and tested this:

isNaN("2")

The above returned false. I am confused here, because the number 2 is in double quotes and i would think it should be considered string?

If i do this:

var sum = "2" + "2"

Result of sum will be "22" which makes sense to me because if you add two strings together the javascript interpreter will concatenate them into one string.

So why is isNaN("2") return false?

Thank you for your help. Nermin

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Not exactly. Some strings can be converted to numbers and others can't. If you type isNaN("hello") you will get back true. This is a string that cannot be converted to a number. However, the string "27" could be converted to a number without error. When this is the case, it will convert the string to a number.

I highly recommend taking a look at the "Examples" section of this MDN Documentation.

Hope this helps! :sparkles:

edited for additional information

On a side note, you might check out this thread where I give some concrete examples of how JavaScript does what is known as "type inferencing". Essentially, JavaScript is pretty smart and can make a best guess about the type of a piece of data by the way you use it.