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 JavaScript Basics (Retired) Making Decisions with Conditional Statements Build a Random Number Guessing Game

Dylan Bailey
Dylan Bailey
2,372 Points

Instead of using parseInt() why not just use a == operator?

Here's my code:

var randomNumber = Math.floor(Math.random() * 6) + 1;
var guess = prompt("I am thinking of a number between 1 and 6...");

if (guess == randomNumber) {
    alert("You got it! The answer was " + randomNumber);
} else {
    alert("Wrong guess :( it was " + randomizedNumber);
}

Is there a downside to using the == operator here or is it basically the same as using parseInt()?

2 Answers

Sean T. Unwin
Sean T. Unwin
28,660 Points

It's mainly for semantics and best practices.

Not sure if this obvious or not, but the contents passed back from the alert is a String, not a Number.

== : Validates the content. This can result in a 'truthy' validation

=== : Validates the content and the type. This is more robust as there is no doubt of truthfulness.

parseInt - will attempt to interpret the content as a Number. So when parseInt(guess) === randomNumber is used it will result an absolute true or false because the content is not only number characters, but the type of content is also a number... or not.

Dylan Bailey
Dylan Bailey
2,372 Points

Ah, I see! Thanks for the response :)

Sean T. Unwin
Sean T. Unwin
28,660 Points

My pleasure. :)

By the way, randomizedNumber in your else statement should be randomNumber.

Won't using the === operator here always result in a false since what is returned from the prompt is always a string?? This is why parseInt is required, correct? Or am I missing something?