Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

This is a basic trivia game I am currently building, but the user's answer is treated as incorrect whether it is correct or not. I think the problem is with the "if" statement, but I'm not sure. Please take a look. Thanks.

[CODE]

var question = 0;
var score = 0;
var questionNumber = 0;

var playerOne = {
score: 0,
};

var playerTwo = {
score: 0,
};

var randomize = function(){
questionNumber = (Math.floor(Math.random()*3+1));
switch(questionNumber){
case 1:
question = "What is the largest country on Earth?";
break;
case 2:
question = "What is the meaning of life?";
break;
case 3:
question = "What is the capital of Columbia?";
break;
};
};

var letsPlay = function(player) {
randomize();
player.score = player.score + 10;
alert("That's right! Could you beee more correct!??" + " " + "Your score is" + " " + player.score);
}else{
player.score = player.score + 0;
};
};

letsPlay(playerOne);
letsPlay(playerTwo);
letsPlay(playerOne);
letsPlay(playerTwo);

[CODE]

• Have you tried using your error console?

Have a look at this line:-

and get rid of the ugly undefined.

if(userAnswer === correctAnswer){ // a good example of why, contrary to felgall's belief, === can cause problems. 42 is not the same as "42", so you must define the answer as a string (which indeed you have done).

You need to look at the calculation of the scores.

The closing code tag is /CODE

Randomizing the questions means that the same question may (and will) appear two or more times. You should instead shuffle the questions into a random order, and then present them sequentially.

I expect you realise that anyone can see the correct answers simply by using View Source.

All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

• ## Users who have thanked Philip M for this post:

nsqui5 (01-23-2014)

• ## Thanks

Thanks for the reply, but what do you mean by the ugly undefined?

• And also what would you recommend other than using "(userAnswer === correctAnswer)"?

• Originally Posted by nsqui5
Thanks for the reply, but what do you mean by the ugly undefined?

shows undefined in the prompt box. Change it to

OK?

• ## Users who have thanked Philip M for this post:

nsqui5 (01-26-2014)

• Originally Posted by nsqui5
And also what would you recommend other than using "(userAnswer === correctAnswer)"?
if(userAnswer === correctAnswer){ is quite OK here, but only because you defined correctAnswer = "42", that is a string rather than a number. I prefer == which would perform the type conversion.. But I have to say that felgall disagrees.

var x = 42; // number
var y = "42" // string
if (x=== y) // false
if (x==y) // true

• ## Users who have thanked Philip M for this post:

nsqui5 (01-25-2014)

•