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

Help: I can't figure out why the alert "Sorry. That is incorrect" pops up even if I enter the correct answer.

Please look at my code and tell me what I'm doing wrong. I don't understand how to approach this challenge at all. I haven't even attempted to do the next step and print the correct answers to the page.

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

var questions = [
  ['What is 2+2?', '4'],
  ['What is the capital of Spain?', 'Madrid'],
  ['Who was the 44th president?', 'Barack Obama']
];
var quiz;
var answer = ' ';


for (var i = 0; i < questions.length; i += 1) {
  var quiz = prompt(questions[i][0]);
  if ( answer === questions[i][1] ) {
      prompt('That is correct!');
  } else {
    if ( answer !== questions[i][1]) {
      alert('Sorry. That is incorrect.');
    };
  }
};

1 Answer

  1. Change var quiz = prompt(questions[i][0]); to answer = prompt(questions[i][0]); First, you've already declared the variable so var is not needed. Second, more importantly, the answers to the questions should be stored in the answer variable not the quiz variable. Right now, the answer variable will always be an empty string; therefore, you will always be alerted Sorry. That is incorrect.
  2. if ( answer !== questions[i][1]) { is unnecessary; just else is enough.

Edit: I've just noticed that you are using the prompt method if the answer is correct, not alert.