Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Arrays Multidimensional Arrays Build a Quiz Challenge – One Solution

I 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
Steven Parker
218,639 Points

Being "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++;
    }
};