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 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,690 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,690 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?