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

Feedback on solution

Refactored code and came up with this solution. But it seems unnecessarily complex to me. Would love any suggestions on how to make this better.

var quiz = [
  ["What are non-wizarding folk called?", "muggles"],
  ["What are the soul sucking, despair inducing creatures called that can be vanquished with a Patronus charm?", "dementors"],
  ["What are the objects into which you can split your soul?", "horcruxes"],
  ["What is Ron Weasley's only sister's name?", "ginny"],
  ["What is Alastor Moody commonly known as? ", "mad eye"],
];

var yourScore = " ";

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

function printCorrectAns(answer){

  var correctMsg = "<h2>You got these questions right: </h2> <ol>";
  correctMsg += answer;
  correctMsg += "</ol>";
  print(correctMsg);
  }

function printIncorrectAns(answer) {
  var incorrectMsg = "<h2>You got these questions wrong: </h2> <ol>";
  incorrectMsg += answer;
  incorrectMsg += "</ol>";
  print(incorrectMsg);
  }


  //check score and post appropriate response

  function checkScore(score, correctMsg, incorrectMsg) {
     if ( score === 0 ) {
       printIncorrectAns(incorrectMsg);
    } else if (score < quiz.length - 1) { 
      printCorrectAns(correctMsg);
     printIncorrectAns(incorrectMsg);
    } else {
      printCorrectAns(correctMsg);
    }
  }


/* function to start quiz - ask a question and add it into a loop
    compare the answer and see if answer was correct.  
 */
function runQuiz() {
  var score = 0;
  var correctMsg = " ";
  var incorrectMsg = " ";
  for (i = 0; i < quiz.length; i++){
    var answer = prompt(quiz[i][0]);
    if (answer === quiz[i][1]){
      correctMsg += "<li>" + quiz[i][0] + "</li>";
      score += 1; 
    } else {
      incorrectMsg += "<li>" + quiz[i][0] + "</li>";
    }
}  

  yourScore += "<b>Your Score is : </b>" + score; 
  print (yourScore);

  /* check if user answered all questions wrong 
     if so don't show the message for correct answers 
     also check whether all answers were correct and 
     finally handle the case when you have mix of correct/incorrect answers
  */

   checkScore(score, correctMsg, incorrectMsg); 

}

runQuiz();