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

Mohamed Ahmed
Mohamed Ahmed
7,449 Points

I did it, but I am feeling my code is weak

I am feeling my code is weak , but this is my best effort

var question = [
    ['What is the capital of UK?', 'london'],
    ['What is the biggest state in the USA?', 'alaska'],
    ['How many states in USA?', '50'],
    ['What is the most popular car in Japan?', 'toyota'],
    ['What is the capital of France', 'paris'],
]; 


var answer = [];


for (var i = 0 ; i < question.length ; i++) {
  answer.push (prompt('Question '+(i+1)+': '+question[i] [0]).toLowerCase());

}

if (answer [0] === 'london') {
    q1 = 1
} else {
    q1 = 0
} if (answer [1] === 'alaska') {
    q2 = 1
} else {
    q2 = 0
} if (answer [2] === '50') {
    q3 = 1
} else {
    q3 = 0
} if (answer [3] === 'toyota') {
    q4 = 1
} else {
    q4 = 0
} if (answer [4] === 'paris') {
    q5 = 1
} else {
    q5 = 0
}

var totalans = q1+q2+q3+q4+q5;

document.write('<p>'+'You Got '+totalans+' Questions Right of '+question.length+'</p>');

document.write('<h2>'+'You Got This Questions Correct:'+'</h2>');

if (q1 === 1) {
document.write('<p>'+question[0] [0]+'</p>')
}
if (q2 === 1) {
document.write('<p>'+question[1] [0] +'</p>')
}
if (q3 === 1) {
document.write('<p>'+question[2] [0]+'</p>')
}
if (q4 === 1) {
document.write('<p>'+question[3] [0]+'</p>')
}
if (q5 === 1) {
document.write('<p>'+question[4] [0]+'</p>')
}

document.write('<h2>'+'You Got This Questions Wrong:'+'</h2>');

if (q1 === 0) {
document.write('<p>'+question[0] [0]+'</p>')
}
if (q2 === 0) {
document.write('<p>'+question[1] [0] +'</p>')
}
if (q3 === 0) {
document.write('<p>'+question[2] [0]+'</p>')
}
if (q4 === 0) {
document.write('<p>'+question[3] [0]+'</p>')
}
if (q5 === 0) {
document.write('<p>'+question[4] [0]+'</p>')
}

You have a lot of repeating scripts that can be consolidated into the for...loop. I'm working on an example to show you right now.

1 Answer

Here is how I would code this jsFiddle

I hope this helps. Feel free to ask me questions if you have any.

Mohamed Ahmed
Mohamed Ahmed
7,449 Points

Thank you very much