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

Colin Grubbs
Colin Grubbs
2,137 Points

isNaN question

I understand in the teacher notes below when he puts "if (isNan(lowNumber) || isNaN(highNumber))" to see if they are numbers.

However, in the video, he just puts "if (lowNumber && highNumber)". I understand that if the the statement in the parenthesis comes out to be true, then the first block runs. But lowNumber doesn't really have a "question" that can be resolved to true. It's just a variable right?

I'm guessing it has something to do with the line: lowNumber = parseFloat(lowNumber) that allows this to work.

2 Answers

If you just put the variable name in parenthesis, it will evaluate true if the variable is defined.

Colin Grubbs
Colin Grubbs
2,137 Points

I see what you're saying. I am going to explain it in length to help myself and others who may not understand.

So basically, as long as lowNumber is defined, it will be true. Otherwise, it will be falsy. When we do parseFloat(lowNumber), the input that the user provides (for example, 6), is a string, but then gets changed to a number. If the user provides something like the number "6", then the input is able to get converted, and therefore has a value of 6 as a number. however, if the user inputs a non-numerical string, say, "dog", the parseFloat(lowNumber) will return NaN and therefore will come out as False in the "if" boolean context. So essentially, the parseFloat() is able to do the job of converting the input to a number as well as checking to see if the input is even a number (because it will be NaN if it is not a number). Therefore, you don't even have to use the isNaN() function in the "if" statement (but you can if you want).