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 Solution

Feedback on my code

Here is my code for this. What can be optimized, done better?

var quiz = [
['Most popular frontend language?', 'javascript'],
['What is summer?', 'season'],
['Most famous markup language', 'html'],  

];
var count = 0;
var resultright = '';
var resultwrong = '';


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


for (var i = 0; i<3; i+=1)  {
var answer = prompt(quiz[i][0]);



if (answer === quiz[i][1]) {
resultright += '<li>' + quiz[i][0] + '</li>';
count = count +1;

} else {
resultwrong += '<li>' + quiz[i][0] + '</li>';
}
}
print('You guessed ' + count + ' questions correct' + '</br>');

print ('You got these questions right:' + '<br>' + '<ol>' + resultright + '</ol>');

print ('You got these questions wrong:' + '<br>' + '<ol>' + resultwrong + '</ol>');

1 Answer

Siddharth Pande
Siddharth Pande
9,046 Points
function print(message) {
  document.write(message);
}

var questArray = [
  ["Which gas helps in burning?","OXYGEN"],
  ["Who is the incumbent Prime Minister of India?","NARENDRA MODI"],
  ["Which state is the Capital of India?","DELHI"]
];

//All the main code is in this function:
function quiz (array) { //array is a parameter where argument will be passed.
  var finalHtml = "<p>" //To produce the Html code

  /*To make the 
  wrong answer Html Code*/
  var wrongStr = "<h4>You got these questions wrong: </h4><ol>" 

  var correctAnswer = 0; // Counter for number of correct guesses

  // To Make the correct Answer Html Code
  var correctStr = "<h4> You got these questions correct: </h4><ol>";

  //Engine(loop) where questions are asked and answers are compared by iterating through the loop and using a decision making if statement.
  for(i=0; i < array.length; i += 1) {
    var guess = prompt(array[i][0]);
    if (guess.toUpperCase() === array[i][1]) {
      correctAnswer += 1;
      correctStr += "<li>" + array[i][0] + "</li>"
    } else {
      wrongStr += "<li>" + array[i][0] +"</li>"  
      }
  }

  //completing the Html code 
  finalHtml += "You got " + correctAnswer + 
  " question(s) right. </p> </br>" +
  correctStr + "</ol> </br>" + wrongStr + "</ol>"; 

  //Printing the final Html code on the document
  print(finalHtml);
}

quiz(questArray); //Run the Program