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 trialMousa Zeidan
2,490 PointsWhy wouldn't while( guess !== randomNumber ) work in this case?
I tried this while condition and it just kept looping. From my understanding this means do (the code) only while your guess is not = to the random number generated. Logically this makes sense but it does not seem to work
am I missing something here :0?
string
3,558 PointsIf you use != it should work cos JS will just try and convert the string (guess) before comparing it to the number/int (randomNumber). But you used the strict inequality operator !==. It really is strict. It will try to compare their data type first even before looking at the values. And in this case, you're comparing a string and a number -- which evaluates to false. parseInt() makes them both actual numbers.
It's considered good practice to always use strict rules and syntax. Relying on JS automatic type conversion should be avoided as much as possible.
1 Answer
Dele Opeifa
11,766 PointsI did it this way and it worked perfectly.
do { guess = parseInt(prompt("I'm thinking of a number between 1 and 10. What is it?")); guessCount += 1; } while ( guess !== randomNumber )
I didn't have to add the extra variable that was used in the last step of the video. I think this is a good way to do it, but maybe I'm missing some potential bugs with this method?
The parseInt() is very important here, because prompt() will return a string, and your randomNumber variable is holding a number. Without parseInt, even if you technically type in the right number, it won't stop the loop, because it will be a string or characters and won't match the correct number.
Adrien Contee
4,875 PointsI also did it this way without using the extra variable. Not sure why the extra false variable is even needed. But maybe later lessons will explain it better.
Mousa Zeidan
2,490 PointsMousa Zeidan
2,490 PointsFigured it out! I forgot to parseInt my guess!
while(parseInt(guess) !== randomNumber) works just fine. Is there any reason why we should stick to the way Dave taught it?