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

Alcibiades Montas
Alcibiades Montas
5,974 Points

Javascript for Quiz App Help

Hi guys, I am trying to build a quiz app and looking into codes and always find something similar to this:

var questions = [
{question: "What is the closest planet to the sun?",
 choices: ["Mercury","Mars","Earth","Saturn"],
 quesNum: 1,
 correctAns: 0},

 {question: "What is the name of the 2nd biggest planet in our solar system?",
 choices: ["Jupiter","Uranus","Pluto","Saturn"],
 quesNum: 2,
 correctAns: 3},

 {question: "What is the hottest planet in our solar system?",
 choices: ["Mercury","Mars","Venus","Earth"],
 quesNum: 3,
 correctAns: 2},
 ];

There seems to be a couple of things going on here:

1) Each question is surrounded by {}, does that mean that each question is an object?

2) In the case that the above is true, each question also has an array inside?

is there an easier manner of setting up a quiz application?

Thanks in advance guys!!

1 Answer

Marc Abrate
Marc Abrate
22,307 Points

Yes. So, I think the following would be true:

questions[0].choices;

would return

["Mercury","Mars","Earth","Saturn"]

and

question[1].choices[2];

would return

"Pluto"

I'm pretty new to javascript, but I would think that you could make the first item in each "choices" array the correct answer, get rid of the "correctAns" variable, and use a function like this.

function checkAnswer ( userAnswer, questionNumber ) {
     if ( userAnswer == questions[ questionNumber ].choices[ 0 ] ) {
          // success
     } else {
          // try again
     }
}

Then run that function whenever the user submits an answer.