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 Solution

guarlonmirka
guarlonmirka
10,192 Points

need help

I have this code but it is not working why? var corectAnswer = 0; var wrongAnswer = 0; var question; var html;

var questionAndAnswer = [ ['What is the capital of Ireland?', 'dublin'], ['What is the capital of France?', 'paris'], ['What is the capital of Portugal?', 'lisbon'] ];

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

for (var i = 0; i <= questionAndAnswer.length; i += 1){ var yourAnswer = prompt(questionAndAnswer[i][0]); yourAnswer.toLowerCase(); if (yourAnswer === questionAndAnswer[i][1]){ corectAnswer += 1; } else { wrongAnswer += 1; } } html = 'you answered ' + corectAnswer + ' questions correctly'; print(html);

What the javascript console say ?

4 Answers

Hey Parkhouse,

I found a few issues with your code. The first two are: the variables corectAnswer [sic] and wrongAnswer are not initialized. You have to initialize these to 0 in order to immediately perform a +1 operation on them.

In your for loop, when iterating over an array, never use <= when making a comparison to a length, because you will go beyond the indices in the array. Always use just a single < operator.

You have to set the variable yourAnswer equal to itself and the "toLowerCase()" method or just call it on the prompt as I do below. Otherwise, "yourAnswer" will not be in lower case form. You have to have somewhere to store the method call.

You're also not using the wrongAnswer variable except to add 1 to it. It's not being outputted anywhere.

var questionAndAnswer = [ 
['What is the capital of Ireland?', 'dublin'], 
['What is the capital of France?', 'paris'], 
['What is the capital of Portugal?', 'lisbon'] 
];
var correctAnswer = 0, wrongAnswer = 0;

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

for (var i = 0; i < questionAndAnswer.length; i += 1){ 
var yourAnswer = prompt(questionAndAnswer[i][0]).toLowerCase(); 
if (yourAnswer === questionAndAnswer[i][1]){ 
correctAnswer += 1; 
} 
else { 
wrongAnswer += 1; 
} 
} 
html = 'you answered ' + correctAnswer + ' questions correctly'; 
print(html);
guarlonmirka
guarlonmirka
10,192 Points

Thanks marcus but can you please explain more why i should never never use <= when making a comparison to a length

When you use <= with the length of an array, the index value used in the for loop goes to the length which is beyond the array's index. For example, with your array, there are 3 main indices: 0, 1, 2 because there are 3 questions and arrays use a numerical index starting at 0. The length of the array is 3. So, by using <=, the for loop is going to an array index 3 at the end of the loop which does not exist in your array and then you get a reference error causing the code to completely stop.

guarlonmirka
guarlonmirka
10,192 Points

great thanks you are a star... do have any advice at the beginning i found JS not that bad to learn but now i find it very hard... and I start thinking to let go, saying to my self it is hard.

There are a lot of resources available to help you learn JavaScript further. The biggest help is going to be changing your mindset to look at problems in a logical manner. I really like the free, interactive course at Codeacademy.com for JavaScript. You can find tons of other resources online for learning JavaScript. Think of a project and start on it. Work on what you can when you can. It'll help your knowledge. And take advantage of the web console if you use Chrome or Firefox (and I think Safari).

MONICA BUI
MONICA BUI
3,526 Points

I found two mistakes in your code, I keeps your code as it is and only fix the mistakes. I also commented to explain why I fix them that way.

var corectAnswer = 0; 
var wrongAnswer = 0; 
var question; 
var html;

var questionAndAnswer = [ 
['What is the capital of Ireland?', 'dublin'], 
['What is the capital of France?', 'paris'], 
['What is the capital of Portugal?', 'lisbon'] 
];

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

for (var i = 0; i < questionAndAnswer.length; i += 1) { // your wrote i <= questionAndAnswer.length; 
    /*
        there are 3 items in your array, if you set i <= 3 (questionAndAnswer.length) 
        then the code-block still run when i = 3, however since the index number start at 0 
        the index number of the 3rd item is 2, there is NO item with the index number of 3
        in other words, the value of i should be the index number available, in this case i = 0, 1, 2
        however in your code you tell the browser to set the value of i = 0, 1, 2, 3
        by doing so you actually tell the browser there are 4 items inside your array
        but in reality there are only 3. Hope this explain your question.
    */
    var yourAnswer = prompt(questionAndAnswer[i][0]); 
    yourAnswer = yourAnswer.toLowerCase(); // your wrote yourAnswer.toLowerCase(); 
    /* 
    you need to set yourAnswer.toLowerCase(); as the new value of the variable named yourAnswer
    */
    if (yourAnswer === questionAndAnswer[i][1]){ 
        corectAnswer += 1; 
    } else {
     wrongAnswer += 1; 
    } 
} 

html = 'you answered ' + corectAnswer + ' questions correctly'; 
print(html);

I've already answered this. It is okay to make code better rather than keep everything the same. If you can combine a method call, you should do it such as attaching "toLowerCase()" to the prompt. It is more efficient and faster to do it this way.

MONICA BUI
MONICA BUI
3,526 Points

Hi Marcus,

So this how I code it, I looked at yours and I did realized that your is more DRY than mine. I learnt from your respond so thank you.

var questionAndAnswer = [
['A', 'A'],
['B', 'B'],
['C', 'C']
];
var correct = 0; 
var wrong = 0; // should have wrote var correct = 0, wrong = 0; 
var ask;

for (var i = 0; i < questionAndAnswer.length; i+=1) {
    ask = prompt(questionAndAnswer[i][0]);
    if (ask.toUpperCase() === questionAndAnswer[i][1]) { 
        correct = correct+=1;
    } else {
        wrong = wrong +=1;
    }
}

function print(meg) {
 document.write(meg)
}

print("<p> You've got " + correct + " correct answers </p>")
print("<p> You've got " + wrong + " wrong answers </p>")

I didn't mean to offend you, if I did then it wasn't intentionally. Different people have different approaches to the same problem. As for me, my priority was to make her/his code WORK first before anything else, I was about to tell parkhouse to create the variable yourAnswer OUTSIDE the loop instead of inside the loop, this has more to do with performance so I decided not to mention it. Since our priorities are different, our responds vary in level of details.

I'm not sure what your priority is, but my priority is to help someone else, which I did. The problem is solved, and I answered the questions Parkhouse asked in an efficient way. I did not take any offense to what you said nor did I imply that. Your comment is completely out of left field to me. Try not to be defensive when responding to someone. It goes a long way.

Btw, the code you posted above has errors. In your "if" and "else" portions, you have correct = correct+=1 and wrong = wrong +=1. These will give you errors and not allow the code to run. These should be correct += 1; and wrong += 1;.

Also, I noticed an error in your original code. You have yourAnswewr = yourAnswer.toLowerCase();. You should either further reference yourAnswewr in the code below that new variable or change that variable to yourAnswer.

MONICA BUI
MONICA BUI
3,526 Points

Hi Marcus,

I tested my code before I public it. It works. You're right about my solutions to parkhouse, should have wrote:

yourAnswer = toLowerCase(yourAnswer);

Thanks!

No, Monica, that is incorrect syntax. Below is the correct format. Nothing ever goes inside the parenthesis of "toLowerCase()". There are a lot of methods like this.

yourAnswer = yourAnswer.toLowerCase();

Keep in mind that although your code might work, it's not in the correct form it should be in. In your 1st set of code, if I put in a different type of capitalization for the answer, it shouldn't matter. But it does with your code because it is setting the value to a different variable that is never used. So, putting in "Dublin" results in a question being marked as wrong. It's just a simple spelling mistake, though, so really just remove the extra w and it's okay and it will work as it should.

In your 2nd set of code, correct = correct += 1 (and the one for wrong answers) works but is redundant. There's no reason to put "correct =" at the front of that statement.

MONICA BUI
MONICA BUI
3,526 Points

Oh, I got it now! Thank a lot Marcus!

Excellent! I'm headed to bed now lol. Good luck, Monica!

guarlonmirka
guarlonmirka
10,192 Points

Thanks guys for all these valuable information.