0

Some one please explain how I can get the score variable to have one added to it each time a question is answered correctly. Each time I run it I get a score of zero when I answer correctly. Thanks.

var questions = [
['What is 1+1?', 2],
['What is 2+2?', 4],
['What is 4+4?', 8],
];

var score = 0;

for(var i=0; i<questions.length; i++)
    {
    var response = prompt(questions [i][0]);
    var correctAnswer = questions[i][1];
    if (response === correctAnswer)
    {
      score += 1;

    } 

    }
document.write('Your score is '+score);


function print(message) {
  document.write(message);
}
2
  • "correct answers" are Number ... prompt returns a string - the two are never equal ... try var response = Number(prompt(questions [i][0])); Commented Oct 3, 2017 at 3:12
  • Or var response = +prompt(questions[i][0]);. prompt() returns its response as a String. Commented Oct 3, 2017 at 3:24

3 Answers 3

1

parseInt the result in prompt because you want is a number..

var questions = [
['What is 1+1?', 2],
['What is 2+2?', 4],
['What is 4+4?', 8],
];

var score = 0;

for(var i=0; i<questions.length; i++)
    {
    var response = parseInt(prompt(questions[i][0]));
    var correctAnswer = questions[i][1];
    if (response === correctAnswer)
    {
      score++;

    } 

    }
document.write('Your score is '+score);


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

Sign up to request clarification or add additional context in comments.

Comments

1

It may be because the response from the prompt is a string & you are comparing with number. Used uniary operator(+) to convert into number before comparison

var questions = [
  ['What is 1+1?', 2],
  ['What is 2+2?', 4],
  ['What is 4+4?', 8],
];

var score = 0;

for (var i = 0; i < questions.length; i++) {
  var response = prompt(questions[i][0]);
  var correctAnswer = questions[i][1];
   //CHanged here
  if (correctAnswer === +response) {
    score += 1;
  }
}
document.write('Your score is ' + score);


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

1 Comment

nice answer.. :)
0

Prompt returns a string, and your answers in the array are stored as numbers. Either change your answers to strings or use == instead of === to check for equality. Using double equals will allow the Javascript engine to be flexible with types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.