Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1 Solution

Different solution

I solved this challenge in a slightly different way.I was wondering if I can get some feedback on my solution?

let correctAnswers = 0;
let questionAnswer = [
  ['Capital of Australia','Canberra'],
  ['Number of states in the United States','50'],
  ['How many colors in the rainbow','7']
];

let answerOne = prompt(questionAnswer[0][0]);
let answerTwo = prompt(questionAnswer[1][0]);
let answerThree = prompt(questionAnswer[2][0]);

let userAnswer = [answerOne, answerTwo, answerThree];

for(let i = 0; i <= 2; i+= 1) {
if ( userAnswer [i] === questionAnswer[i][1]) {
  correctAnswers += 1;
}
else {
  correctAnswers = correctAnswers;
}
}

var html = '<p>' + 'You got ' + correctAnswers + ' question(s) right.' + '</p>' 

document.write(html);

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

3 Answers

Steven Parker
Steven Parker
210,425 Points

Suggestions and observations:

  • you could ask the questions as part of the loop instead of with separate statements
  • the loop limit could be the length of the questions array instead of an explicit number
  • the code body of a loop can be indented to indicate nesting level
  • assigning a value to itself has no effect, so the entire "else" can be eliminated
  • the "print" function was defined but never used

Steven Parker Thank you for your thoughtful feedback and suggestions.The print function was there by default. I couldn't figure out what is the purpose of this function?

Steven Parker
Steven Parker
210,425 Points

I believe in the video it is used as a replacement for "document.write" in the main code area.

Steven Parker That's true.Thanks.