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 trialRiadh Hamidou
Full Stack JavaScript Techdegree Student 3,711 PointsWhy does (correctGuess = false) not work ?
Hi, I wrote the code like below , but it looks like the correct way to do it is like this (!correctGuess).
What is the difference ?
var randomNumber = getRandomNumber(10);
var guess;
var guessCount = 0;
var correctGuess = false;
function getRandomNumber( upper ) {
var num = Math.floor(Math.random() * upper) + 1;
return num;
}
do {
guess = prompt("I am thinking of a number between 1 and 10. What is it?");
guessCount += 1;
if (parseInt(guess) === randomNumber) {
correctGuess = true;
}
} while (correctGuess = false) // This condition doesn't work and it writes the final message to the document after the first guess no matter what the guess is
document.write("<p>It took you " + guessCount + " attempts to guess the number " + randomNumber + ".</p>");
2 Answers
Riadh Hamidou
Full Stack JavaScript Techdegree Student 3,711 PointsYeah, this is why they say javascript turns coffee into code. I needed that coffee.
I read somewhere else that you can't assign in the condition, and despite that, I was staring at it thinking I've done nothing wrong, I just wrote ( ! correctGuess ) in another way. :D
I tried it again and it worked just as fine.
Thank you
Thomas Nilsen
14,957 Pointsdo {
//rest of code..
} while (correctGuess = false)
You can't assign a variable in the while-part. You have to actually check if it equals some value.
It should look like this:
do {
//rest of code..
} while (correctGuess === false) //Notice - **not** just one equal-sign
Audra Ogilvy
3,142 PointsOMG. Thank you, Thomas!!!!! That answer really, really helped.
So, is there a difference between a variable created using the var keyword, and a variable created just with the equals operator? In other words, is this: var guess = false different than this: guess = false ?
Riadh Hamidou
Full Stack JavaScript Techdegree Student 3,711 PointsRiadh Hamidou
Full Stack JavaScript Techdegree Student 3,711 PointsAnd this code works too, Is there big differences between the two methods, is one more preferred than the other ? Sorry, I'm not sure how to embed code