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
Abbey Warzynski
Full Stack JavaScript Techdegree Student 3,650 PointsMy code works! Any better suggestions?
var questions = [
["How old am I?", 36],
["How old are you?", 46],
["What is 2+2?", 4],
];
var correctAnswers = [];
var incorrectAnswers = [];
var answers = [];
var answersNum = [];
var result;
var numbers;
function print(message) {
document.write(message);
};
for (var i = 0; i <questions.length; i+= 1) {
var result = prompt(questions[i][0]);
answers.push(result);
}
for (var i = 0; i < answers.length; i+= 1) {
var numbers = parseInt(answers[i]);
answersNum.push(numbers);
}
for (var i = 0; i < answersNum.length; i+= 1) {
if (answersNum[i] === questions[i][1]) {
correctAnswers.push(questions[i][0]);
} else {
incorrectAnswers.push(questions[i][0]);
}
}
function printList(list) {
var printHTML = "<ol>";
for (var i = 0; i < list.length; i++) {
printHTML += "<li>" + list[i] + "</li>";
}
printHTML += "<ol>";
print(printHTML);
}
print("<p>You got " + correctAnswers.length + " answers correct </p>");
print("<h2> Here are the questions you answered correctly: </h2>");
printList(correctAnswers);
print("<h2> Here are the questions you answered incorrectly: </h2>");
printList(incorrectAnswers);
Iain Simmons
Treehouse Moderator 32,305 PointsAdded code formatting
1 Answer
Robert Stefanic
35,170 PointsHi Abbey,
Great work!
I do have a suggestion though.
At the top, in the global space, you have these two variable declarations:
var result;
var numbers;
But then within each of your foor loops, you define these variables again; but you don't have to repeat yourself.
By the way scope works, you're creating these local variable within your for loops, and the global variables that you defined are never being used! So you can get rid of the the the result and numbers declarations in the global space (the top of your file), and just leave the local ones that you defined within each for loop.
Steven Parker
243,356 PointsSteven Parker
243,356 PointsJust a suggestion for posting code:
Use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area.
Or watch this video on code formatting.