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 Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1

Edwin Carbajal
Edwin Carbajal
4,133 Points

One of many ways!

var questions = [
  ['What is the best programming language?', 'javascript'],
  ['What keyword is used to declare a variable?', 'var'],
  ['What method is available to insert new items at the end of an array?', '.push()']
];
var correctGuesses = 0;
var correctQuestions = "<h2>You got these questions correct:</h2><ol>";
var incorrectQuestions = "<h2>You got these questions wrong:</h2><ol>";

function print(message) {
  document.write(message);
}

function printCorrect(string) {
  string += "</ol>";
  print(string);
}

function printIncorrect(string) {
  string += "</ol>";
  print(string);
}

function quiz() {
  for ( var i = 0; i < questions.length; i++) {
    var response = prompt(questions[i][0]).toLowerCase();
    if (response === questions[i][1]) {
      correctGuesses += 1;
      correctQuestions += "<li>" + questions[i][0] + "</li>"
    } else {
      incorrectQuestions += "<li>" + questions[i][0] + "</li>"
    }
  }
  print('<p>You got ' + correctGuesses + ' right.</p>');
  printCorrect(correctQuestions);
  printIncorrect(incorrectQuestions);
}
quiz();

1 Answer

I like how modular this is. I have yet to refactor my code.

The only tweak I made in mine was to add a check to see if the score is 0 and to only print out incorrect answers. I also added a check to see if the maximum score was reached and then printed out correct answers.