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
Khoa Le
3,360 PointsWorks but a lot of repeated code. what's the way to make it better?
var correct = 0;
questionsLeft = 5;
var q1 = prompt("What's your name?");
if(q1.toLowerCase() === "sam") {
alert("You got it right");
correct += 1;
} else {
alert("You got it wrong");
questionsLeft -= 1;
alert("You have " + questionsLeft + " questions left");
}
var q2 = prompt("What street do you live on?");
if(q2.toLowerCase() === "jersey") {
alert("You got it right");
correct += 1;
} else {
alert("You got it wrong");
questionsLeft -= 1;
alert("You have " + questionsLeft + " questions left");
}
var q3 = prompt("what city do you live in?");
if(q3.toLowerCase() === "chicago") {
alert("You got it right");
correct += 1;
} else {
alert("You got it wrong");
questionsLeft -= 1;
alert("You have " + questionsLeft + " questions left");
}
var q4 = prompt("What is favorite bank?");
if(q4.toLowerCase() === "chase") {
alert("You got it right");
correct += 1;
} else {
alert("You got it wrong");
questionsLeft -= 1;
alert("You have " + questionsLeft + " questions left");
}
var q5 = prompt("what is your favorite online learning website?");
if(q5.toLowerCase()=== "treehouse") {
alert("You got it right");
correct += 1;
} else {
alert("You got it wrong");
questionsLeft -= 1;
alert("You have " + questionsLeft + " questions left");
}
document.write("<p>" + "You got " + correct + " correct answers" + "</p>");
if( correct === 5) {
document.write("<p>" + "You got the gold crown" + "</p>");
} else if (correct === 3 || correct === 4) {
document.write("<p>" + "You got the silver crown" + "</p>");
} else if (correct === 1 || correct === 2) {
document.write("<p>" + "You got the bronze crown" + "</p>");
} else {
document.write("<p>" + "You got 0 crown" + "</p>");
}
1 Answer
Steven Parker
243,656 PointsTry using a function to compact your code.
Those blocks of code for each question are very similar except for the question string and the answer. You could define a function that takes those items as parameters and then call it for each question.