Bummer! You must be logged in to access this page.

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

So, what's up with my code, it wont print the last line.

var qa = [
    ['what is 1+1', 2],
    ['what is 1+2', 3],
    ['what is 1+3', 4]
];
var correctA = 0;
var q;
var a;


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

for ( var i = 0; i <= qa.length; i +=1) {
    q = parseInt(prompt(qa[i][0]));
    a = qa[i][1];
if ( a === q ){
    print('<p>Correct answer</p>');
    correctA +=1;
}else {
    print('wrong answer </br>');
    correctA -=1;
}

}

print('<h2>Correct answers: ' + correctA + '</h2>');

2 Answers

You need to change your for loop statement to run the same amount of times as qa.length.

Currently you have i = 0 and i <= qa.length. Since qa.length is equal to 3, the loop is attempting to run 4 times.

Two ways to fix this (choose one method from below):

  1. Set i to 1
  2. Have i < qa.length (i.e remove the equals sign, from "<=" to be "<")

Hi,

Does it work if you move your print statement to just before your last '}'?

it does, but it goes inside a loop

I tried doing it with out a function and with counsole.log, nothing works. Seams like a program just stops as soon as it finished the loop

It does seem odd (sorry, it's been a while since I've dealt with Javascript). Just for fun... try wrapping that last print statement in a separate for loop that only runs once.