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!

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 JavaScript Numbers The Math Object Random Number Challenge – Solution

Octavian Runceanu
Octavian Runceanu
6,143 Points

if (highNumber) question

I don't understand the following block: if (highNumber) { } What does this condition do? It's the same as if (highNumber == true) ?

And if yes, how is compared a number with a boolean . I do not get it. Can someone please explain this concept to me?

1 Answer

It works in JavaScript the same as if (highNumber == true) if highNumber were a boolean, but it's not a boolean, so how does it work? I understand your confusion. The answer is that when not provided with a value to compare to, the conditional checks if it is "truthy" or "falsey" by deciding that some values are inherently true and some are inherently false. For example, when checking numbers, a zero ( 0 ) is considered false, whereas a 1 (or any other number) is considered true. This way of coding makes it easier and shorter to write code that accomplishes the same thing, without having to put in lots of checks for bad values. In reality, if (highNumber) {} is really more like: if (highNumber > 0 && highNumber != null && highNumber != NaN && highNumber != undefinded && highNumber != false){}. This is very useful when you might be checking against a value that might be undefined or evaluates to an error, like NaN (which is one thing that could happen in this challenge). I hope that helps.

Another thing I should mention is that I don't really like the alert message, as it tells the user to enter a number, but if you put in a zero, it will also fail the condition, so the message should really say "You need to provide a number greater than one"

Tony Shangkuan
Tony Shangkuan
6,720 Points

Thanks for the clarification!! I had the same question!