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 trialHina K.
4,806 PointsI interpreted the challenge differently. How can I make this code DRY?
let quiz = [
["Who is the president of the United States?",
"How many states are in the US?",
"What is the capital of California?",
"Name the ocean on the west coast.",
"Name the country north of the US.",
"How many colors are in the US flag?"],
["Biden", '50', "Sacramento", "Pacific", "Canada", '3']
];
let counter = 0
for (let i = 0; i < quiz[0].length; i++) {
let answer = prompt(quiz[0][i]);
if (answer === quiz[1][0]) {
counter++};
if (answer === quiz[1][1]) {
counter++};
if (answer === quiz[1][2]) {
counter++};
if (answer === quiz[1][3]) {
counter++};
if (answer === quiz[1][4]) {
counter++};
if (answer === quiz[1][5]) {
counter++};
if (answer === quiz[1][6]) {
counter++};
if (answer === quiz[1][7]) {
counter++};
};
console.log(counter);
document.querySelector('main').innerHTML = `<h1>Out of 6, you got ${counter} questions correct.</h1>`
1 Answer
Steven Parker
231,248 PointsBeing "DRY" isn't the biggest issue here, there is a basic logic problem. To illustrate the problem, try giving the same answer (like "50") to every question and the program will consider them all correct. You'll want to adjust the checking strategy to make sure only the correct answer for each question is counted. Eliminating the redundant checks will also make the code more "DRY" at the same time. For example:
for (let i = 0; i < quiz[0].length; i++) {
let answer = prompt(quiz[0][i]);
if (answer === quiz[1][i]) { // check ONLY this question's answer
counter++;
}
};