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 Improving the Random Number Guessing Game

Jennifer Hughes
Jennifer Hughes
11,421 Points

Why start with: var correctGuess = false?

In this challenge, why do we start with:

var correctGuess = false

?

3 Answers

Herb Bresnan
Herb Bresnan
10,658 Points

I didn't quite get it either until I changed it to false just to see what would happen. It really helped me by looking at it line by line as the program ran.

It will evaluate the first condition to true or false. If it is false it will pass to the else if() condition. Your second guess no matter what number you put in, 15 for example, will always evaluate to true and you win every time.

I think this is because the first nested if statement is saying the variable correctGuess is true, so it passes straight through to 'You guessed the number!' to end the program.

Kyle Daugherty
Kyle Daugherty
16,441 Points

It's needed so the if/else statement that will print out if the user guessed correctly or not will work properly. You could also have just defined the variable but not assigned a value like so since null is also a falsy value:

var correctGuess;

Think of it as changing states. The prompted guess is changing the state of variable, like turning on a light bulb that is off.