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 Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1

Daniel Stoica
Daniel Stoica
2,430 Points

I did it without loops...is that bad?

I managed to do it without loops, I am not sure if this made it more efficient or not, it just the first way that came to mind:

var questions = [['How are you?', 'Fine.'], ['What is your name?', 'Daniel'], ['Where are you from?', 'Romania']]; var answers = 0;

var answer1 = prompt('How are you?'); if (answer1 === questions[0][1]) { answers+=1; }; var answer2 = prompt('What is your name?'); if (answer2 === questions[1][1]) { answers+=1; }; var answer3 = prompt('Where are you from?'); if (answer3 === questions[2][1]) { answers+=1; };

message = 'You answered correctly for ' + answers + ' questions.';

function print(message) { document.write(message); }

print(message);

1 Answer

andren
andren
28,558 Points

The point of using a loop is that it makes your code far shorter, more concise, and more scalable. Also without using a loop you aren't really making use of the two-dimensional array. If you only pull out answers from the array then a normal array would have sufficed.

The point of having the array be two-dimensional was specifically to allow you to pull out both the question and answer as you looped though it. With a two-dimensional array you can also expand the quiz simply by adding new items to the array.

With only 3 questions there isn't that much difference code and time wise between the two approaches, but if you let's say had a quiz with 40 questions. That would not result in that much code with the loop and two-dimensional array approach, but with your approach would result in tons of duplicate code that would have to be written manually.

I'm sure you can understand how in that situation the loop approach would be far more efficient.

Daniel Stoica
Daniel Stoica
2,430 Points

I get it now. Thank you very much!