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

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,