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

The second if-statement is not really necessary, right?.

Why is the second if-statement necessary? I do not think it is but I understand the point of it. The first if statement assigns the true-value to the correctGuess-variable if the number is accurate. Otherwise correctGuess maintain its false-value. Then in the second if-statment you strictly equally compare if correctGuess is true and the document.write takes over. Otherwise if false, the else{} is used.

Below is how I wrote the code with the document.write from the 2nd if-statement located in 1st if-statement instead, as it already test the condition if correctGuess === randomNumber.

if (parseInt(guess) === randomNumber ) {
  correctGuess = true;
  document.write('<p>You guessed the number!</p>');
} else {
    document.write('<p>Sorry. The number was ' + randomNumber + '.</p>');
}

2 Answers

Steven Parker
Steven Parker
230,274 Points

You didn't show the original code, but based on your description it sounds like you have performed an effective refactoring of the code and have eliminated the need for the "correctGuess" variable. Good job! :+1:

You can also remove the assignment and initialization (not shown here) at this point.

You'll have more opportunities to practice your refactoring skills in other video projects, since they focus on teaching a particular technique many are not completely optimized.

Hi Steve!

Thanks for the fast feedback. Here is the original code and tell if it something I don't regard having the second if-statement

var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');
if (parseInt(guess) === randomNumber ) {
  correctGuess = true;
} 

if(correctGuess === true){
  document.write('<p>You guessed the number!</p>');
}

else {
    document.write('<p>Sorry. The number was ' + randomNumber + '.</p>');
}
Steven Parker
Steven Parker
230,274 Points

It looks like you understood it perfectly.

Steven Parker
Steven Parker
230,274 Points

Antonio Ascue Avalos — If your original question has been answered, you can mark it solved by choosing a "best answer".
And happy coding!