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

Gavin Broekema
seal-mask
.a{fill-rule:evenodd;}techdegree
Gavin Broekema
Full Stack JavaScript Techdegree Student 22,443 Points

45 line solution. Feedback please?

var questions = [
  ["Which language is typically used to structure a webpage?", "html"], 
  ["Which language is typically used to add presentation to a webpage?", "css"], 
  ["Which language is typically used to add behavior to a webpage?", "javascript"]
];
var correct = 0;
var incorrect = 0;
var answer;
var right = [];
var wrong = [];

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

function grade (marks) {
  var response = "";
  response += '<ol>';
  for (var i = 0; i < marks.length; i++) {
    response += '<li>' + marks[i] + '</li>';
  }
  response += '</ol>';
  print(response);
}

for (var i = 0; i < questions.length; i += 1) {
  answer = prompt(questions[i][0]);
  answer = answer.toLowerCase();
  if (answer === questions[i][1]) {
    correct++;
    right.push(questions[i][0]);
  } else {
    wrong.push(questions[i][0]);
    incorrect++;
  }
}

print('<p>You got ' + correct + ' question(s) correct.<br>');
if (correct > 0) {
  print('<strong><p>You got these questions correct: </p></strong>');
  grade(right);
} else if (incorrect > 0) {
  print('<strong><p>You got these questions incorrect: </p></strong>');
  grade(wrong);
}

I decided to remove the opposing statement if all questions were answered correctly/incorrectly for a little extra challenge. Tried to answer this challenge as succinctly as possible, but there's obviously always room for improvement! Please let me know if/how I could make this program more concise (while keeping it maintainable/readable of course). Thanks!

2 Answers

You can also condense your var declarations:

var questions = [
  ["Which language is typically used to structure a webpage?", "html"], 
  ["Which language is typically used to add presentation to a webpage?", "css"], 
  ["Which language is typically used to add behavior to a webpage?", "javascript"]
],
correct = 0,
incorrect = 0,
answer,
right = [],
wrong = [];
alastair cooper
alastair cooper
30,617 Points

very good.

You could condense this:

 var response = "";
  response += '<ol>';

to

 var response = '<ol>';

not much different, but 1 less line to compile