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 trialTomas Vesely
1,090 Pointsprogram prints both if and else answers
if (userAnswer1.toUpperCase() === answer1) {
document.write('That is correct! You earned 1 point.');
var score = 1;
} else (score = 0);{
document.write('Sorry that is not correct');
}
Above is my code and when I run it with to correct answer both "correct" and "not correct" answers print in the page.. please help. Thank you!
Sabine Kroess
2,401 PointsFor me your else comment looks weird. Try the changing it to:
else { document.write ("Sorry that is not correct"; score = 0 }
something else: Where did you declare the variable score? I did it before the conditional statement - initializing the value to 0; Like: var score = 0; before the if-else statement because only one of the 2 branches "run". In the branch with the correct answer I add 1 to the score like: score +=1; in the branch with the wrong answer I do nothing.
Do you understand what I mean?
3 Answers
Tomas Vesely
1,090 PointsThank you! it worked... can I then set the score to 0 in the else statement to keep track of the score like I did in the if statement?
Tim Acker
Front End Web Development Techdegree Graduate 31,247 PointsYou could, but there is really no need too. Plus, if you are asking multiple questions and want to track the total score, using 'score = 0' in the else statement will not work. In this case, declare the variable outside of the if...else statement by adding 'var score;' and replace 'var score = 1' with 'score += 1'. This will increase the total count by one.
Sabine Kroess
2,401 Points``` var score = 0;
if (userAnswer1.toUpperCase() === answer1) { document.write('That is correct! You earned 1 point.'); var score += 1;} else {document.write('Sorry that is not correct'); } ```
Sabine Kroess
2,401 Pointssorry, I did it wrong - leave the var keyword out inside the if statement.
Tomas Vesely
1,090 PointsHey no problem! I know what you mean and already changed it and it makes complete sense thanks for help!
Tim Acker
Front End Web Development Techdegree Graduate 31,247 PointsTim Acker
Front End Web Development Techdegree Graduate 31,247 PointsTry something like this: