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 trialRishabh Kumar
2,649 PointsHow can I improve this Code?
I've Written this code but would like to know how to make it better!
function print(message) {
document.write(message);
}
var rightCounter = 0;
var wrongCounter = 0;
var rightAns=[];
var wrongAns=[];
var queAns = [
['What is the Capital of India?' , 'New Delhi'],
['What is the name of the capital of the UK','London'],
['WHat is the name of the Capital of the US', 'Washington D.C.']];
for ( i =0; i<3; i++) {
var question = prompt(queAns[i][0]);
if (queAns[i][1]===question){
rightAns.push(question);
rightCounter ++;
}else {
wrongAns.push(question);
wrongCounter ++;
}
}
print('Hey you have got ' +rightCounter + ' right answers and ' + wrongCounter + ' wrong answers. <p> Your right answers include: </p>'+ rightAns +' <p>and wrong answers include:</p><p>' + wrongAns+ '</p>' );
1 Answer
Brian Daigle
8,190 PointsThat looks good to me but if your looking to futz with it more. The things I thought of while reading it were.
Use a .toLowerCase() or .toUpperCase() when comparing inputted answer with correct answer.
I'd use "i < quesAns.length" instead of "i < 3" in case the number of questions changes.
Unless you are planning to do something with them, the rightAns and wrongAns variables aren't really necessary since you only display the rightCounter and wrongCounter variables. I do like the idea of keeping track of which questions were right and wrong, though maybe it would be better to just keep track of the array position of the question by doing ".push(i)" Then it would be easy to grab both the question and the answer from the queAns array if you wanted to later on.
With the last question especially, you might want to try adding multiple right answers since it could be written "Washington DC", "District of Columbia", etc. This would mean changing the way you check for a right answer though, probably using .indexOf().
LaVaughn Haynes
12,397 PointsLaVaughn Haynes
12,397 PointsI fixed this so that your code displays correctly. Click on the Markdown Cheatsheet link below text areas to see how it works.