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 trialDylan Bailey
2,372 PointsInstead 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
28,690 PointsIt'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.
Alexander Soroka
3,769 PointsWon'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?
Dylan Bailey
2,372 PointsDylan Bailey
2,372 PointsAh, I see! Thanks for the response :)
Sean T. Unwin
28,690 PointsSean T. Unwin
28,690 PointsMy pleasure. :)
By the way,
randomizedNumber
in yourelse
statement should berandomNumber
.