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

This is the solution I came up with, tips and criticism needed!

var answer = "";
var rightAnswers = 0;
var questionNumber = 1;

var questions = [
  ['What programming language is named after a gem?', 'ruby'],
  ['What do you use to type?', 'keyboard'],
  ['What is the acronym for the programming phrase "Dont repeat yourself"?', 'dry'],
  ['JavaScript is an amazing language right?', 'yes']

];


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

function startQuiz(loop) {
  for (i = 0; i < loop.length; i += 1) {
    answer = prompt('[' + 'Question ' + questionNumber + '] ' + loop[i][0]);
    questionNumber += 1;
    if (answer.toLowerCase() === loop[i][1]) {
      rightAnswers += 1;
    } 
    var done = 'You got ' + rightAnswers + ' out of ' + questions.length + ' correct. ';    
 }
print(done);  
}

startQuiz(questions);

1 Answer

aapo
aapo
2,677 Points

Here's a few things to improve on:

  1. Do not create the done variable inside the for loop. This is unnecessary and can be done one time, right after the for loop ends. Move the line out of the loop.

  2. Don't use questions.length when creating the done variable, use loop.length as you used in the for loop. The reason for this is that you may not necessarily use the questions variable when you call startQuiz, and this could lead to errors.

  3. Rename the loop variable! Try something more descriptive like questionArray

Hope this helped! (:

Thanks for the response Aapo!

1.) Makes sense, should I still keep it within the function? Or move the variable to the top of the doc and just change it within the function.

2.) Not exactly sure what I was thinking there haha. Changed it though.

3.) Right, I would imagine that would make it easier for myself and others when you're working with a ton of code. I'll make sure going forward I'm a little more descriptive haha.

Thanks again,