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!
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

Ivan Marchenko
8,962 PointsSo, 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

Sean T. Unwin
28,688 PointsYou 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):
- Set
i
to 1 - Have
i < qa.length
(i.e remove the equals sign, from "<=" to be "<")

Jon Kussmann
Courses Plus Student 7,254 PointsHi,
Does it work if you move your print statement to just before your last '}'?

Ivan Marchenko
8,962 Pointsit does, but it goes inside a loop

Ivan Marchenko
8,962 PointsI 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

Jon Kussmann
Courses Plus Student 7,254 PointsIt 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.