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 Arrays Multidimensional Arrays Build a Quiz Challenge – One Solution

Why can’t I just do this?

In the video, Guil makes a question variable inside the loop and uses it to get the questions in the multidimensional array. Why can’t we just make it shorter and do this?

for (let i = 0; i < questions.length; i++) { let answers = prompt (questions[i][0]); }

I tried this and it didn’t work, if someone can explain why it doesn’t work and why you need another variable, that would be much appreciated. Thanks!

4 Answers

Steven Parker
Steven Parker
229,732 Points

What you did does make the code more compact by eliminating the need for the third variable (question), but you still need the other two to hold the correct answer (answer) and what the user inputs (response).

You could take the concept further and eliminate all the variables by folding the values into the conditional expression, though it might be a bit more complicated to read:

for (let i = 0; i < questions.length; i++) {
  if (prompt(questions[i][0]) === questions[i][1]) {
    correctAnswers++;
  }
}

Ok, thanks!

Just to confirm, the questions variable isn’t necessary, but the answer and response variables are? An additional question; why does the answer variable need to be declared instead of just directly putting it into the conditional statement from the array itself? Does it have something to do with the variable scopes?

Steven Parker
Steven Parker
229,732 Points

Take another look at my example, it does eliminate all 3 variables by using the the array in the conditional.

This works for me.

for(let i = 0; i < questions.length; i++){
  let answer = prompt(questions[i][0]);
  if(answer){
    answer = answer.toLowerCase();
  }
  if(questions[i][1] === answer){
    correct ++;
  }
}

This works for me

for (let i = 0; i<quizList.length; i++){ let quiz = prompt(quizList[i][0]); if (quiz=== quizList[i][1]){ console.log(${answer}); answer++; } }