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 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
210,423 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
210,423 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 ++;
  }
}
Jessy Lee
Jessy Lee
6,932 Points

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++; } }