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

Use of AND and OR operator for a Quiz program.

I am attempting to associate a score/award based on the amount of questions that a player gets right. The solution in my head is to use the mentioned operators to come up with every combination (for example: Q1 (WRONG) Q2, Q3, Q4, Q5 (RIGHT). Q1 (RIGHT) Q2 (WRONG) Q3, Q4, Q5 (RIGHT). Q1, Q2 (WRONG) Q3, Q4, Q5 (RIGHT). And so on) and associate them with Boolean values related to the right award. This seems extremely long winded and was wondering if the was an easier to achieve my goal.

3 Answers

Are you awarding different scores for different questions?

Or is it just that different questions have different categories?

You can use a string to check for scores in the end.

//A string that catalogs answer 'status' of each question.
let score = ""; 

Now just append an integer or a character to the score as the player progresses. For eg:

//Iterate through questions
   //If (condition: player answers a question right)
   score = score + "1";
   //Else
   score = score + "0";
//Now match string to a regex that searches for 0's or 1's
//If score.match("/0/g").length == 0, then 0 questions are correct and so on.

Using this you can even have markings in your question other than 0's and 1's, like a scale from 1 to 3 and then check status of questions answered by matching to appropriate regex's.

And for reference check this out!: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

It's a game where based on how many questions you get right e.g 5 questions = gold 3-4 =silver 2 = bronze 0-1 = nothing.

Thanks for your answer

let award = ""; //Gold, Silver or Bronze

//If 5 questions right, 5 1's appended
if(score.match("/1/g").length == 5){
   award = "gold";
}
else if(score.match("/1/g").length > 2){
   award = "silver";
}
else if(score.match("/1/g").length == 2){
   award = "bronze";
}
//For 0 or 1 right question
else {
   award = "";
}

Hope these conditions solved your problem. If yes, please mark your question as 'solved', but if you still have trouble please write back.