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 JavaScript Arrays Multidimensional Arrays Build a Quiz Challenge – One Solution

Sufiyaan Haroon
seal-mask
.a{fill-rule:evenodd;}techdegree
Sufiyaan Haroon
Full Stack JavaScript Techdegree Student 9,558 Points

Can my code be better or be writtien easier:

This is my version but what are some changes I can make to make it more easier to read and to make is more simple:

*"guess" is the response

const quizQA = [
  ['Name?', 'sufi'],
  ['How many planets are there?', '8'],
  ['When was javascript created?', '1995']
]
let guess;
let correct = 0;

for (let i = 0; i < quizQA.length; i++) {
  guess = prompt(quizQA[i][0]);
  let answer = quizQA[i][1];
  if (guess.toLowerCase() === answer) {
    correct++;
    console.log(correct);
  }
}


document.querySelector('main').innerHTML = `<h1>You got ${correct}/${quizQA.length} correct!</h1>`;

3 Answers

Steven Parker
Steven Parker
229,771 Points

This looks simple and easy to read as is! Good job. :+1:

My only suggestion is that it seems odd to declare "guess" outside the loop but "answer" inside. It might look better with them declared in the same place. Either place will work fine, but since they are only used inside the loop that might be the optimum placement.

Patrick Koch
Patrick Koch
40,496 Points

You could do it more simple but it looks fine for me.

let questions = [
    ['Question 1', 'Answer1'],
    ['Question 2', 'Answer2'],
    ['Question 3', 'Answer3'],
]

let correct = 0;

for(let i = 0; i < questions.length; i++){
    if( prompt(questions[i][0]) === questions[i][1].) correct++;
}

alert(`Correct Answers ${correct}`);
Steven Parker
Steven Parker
229,771 Points

Looks like there's a stray period on this line:

    if( prompt(questions[i][0]) === questions[i][1].) correct++;
//                                                 ^ here

Also, while simpler, this code is not quite functionally identical to the original.

Patrick Koch
Patrick Koch
40,496 Points

true ;.-) missed that one.