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

Any suggestions on improving my response?

//This sets up the questions and answers to be asked and requested
var questionArray = [ [' I did it my way', 'Frank Sinatra'],
  ['Respect', 'Aretha Franklin'],
   ['Imagine', 'John Lennon'],
  ['Born to Run', 'Bruce Springsteen'],
  ['Louise Louie', 'The Kingsmen'],
  ['Maybeline', 'Chuck Berry']];


// This creates a function that will be used to write all of the questions to the page
function printQuestion(question) {
  var listQuestion = '<h1>Random Questions <br> <ol>';
  for(var i=0; i < question.length; i+=1){
    listQuestion += '<li> Who sang ' + question[i][0] + '?</li>';
  }
  listQuestion += '</ol>' + '</h1>';
  document.write(listQuestion);
}

// This creates a function that asks the questions listed in the master array. It also keeps track of how many guessed correctly and incorrectly.
function askQuestion(apple){
  counterCorrect = 0;
  counterWrong = 0;
  for (var i=0; i < apple.length; i += 1){
    var response = prompt( 'Who sang this song, ' + apple[i][0]);
    if (response === apple[i][1]){
          counterCorrect += 1 ;
      } else{
          counterWrong += 1;
      }
}
  // This writes the results of the quiz
document.write("<p>You have answered " + counterCorrect + " of " + apple.length + " questions correctly.</p>" + "<p>You have missed " + counterWrong + " of " + apple.length + " questions correctly.</p>");
}


//This runs the two functions.
printQuestion(questionArray);
askQuestion(questionArray);

1 Answer

Instead of using document.write, considering writing a print function that interacts with the page using innerHTML. Better yet, you could instead create DOM elements using document.createElement and then append to specific elements using .appendChild.

Otherwise your code looks pretty good to me, nice job! :)