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 trialEkaterina Svobodina
4,875 PointsJavaScript adds undifined when printing to the page.
So I haven't looked at the solution yet, because I want to understand why this code does what it does. It works, and print to the page what I want except it adds undefind:
This is what I want it to print:
You got 2 question(s) right. You got these question(s) correct:
How many states are there in the USA?
How many oceans are there?
You got these question(s) wrong:
- How many continents are there?
And this is what it prints:
You got 2 question(s) right. You got these question(s) correct: undefined
How many states are there in the USA?
How many oceans are there?
You got these question(s) wrong:
undefined
- How many continents are there?
Here is my code:
var qAndA = [
['How many states are there in the USA?', 51],
['How many continents are there?', 7 ],
['How many oceans are there?', 5]
];
//var q1 = parseInt(prompt(qAndA[0][0]));
//var q2 = parseInt(prompt(qAndA[1][0]));
//var q3 = parseInt(prompt(qAndA[2][0]));
var i;
var q;
var correct;
var notCorrect;
var correctN = 0;
var notCorrectN = 0;
var messageA;
var messageB;
for ( i = 0; i < qAndA.length; i += 1){
q = parseInt(prompt(qAndA[i][0]));
if (q === qAndA[i][1]) {
correctN +=1;
correct += '<p>' + correctN + '. ' + qAndA[i][0] + '</p>';
} else {
notCorrectN +=1;
notCorrect += '<p>' + notCorrectN + '. ' + qAndA[i][0] + '</p>';
}
}
function print(messageA) {
messageA = document.write('<div><h2>You got ' + correctN + ' question\(s\) right.</h2>' +
'<b> You got these question\(s\) correct: </b>' +
correct + '</div>' );
if (notCorrectN > 0) {
messageB = document.write(
'<p><b> You got these question\(s\) wrong: </b></p>' +
'<p>' + notCorrect + '</p>');
messageA += messageB;
}
return messageA;
}
print(messageA);
2 Answers
akak
29,446 PointsWhen you define variable like:
var i;
var q;
var correct;
var notCorrect;
its initial value is "undefined".
If you overwrite variable after declaration with a new value it's not a problem. But if you're going to concatenate, then you need to declare them initially as an empty string.
Ekaterina Svobodina
4,875 PointsThank you very much! It worked just like you said.