T. Evans
T. Evans

Reputation: 1011

Alert message is wrong

I am currently new to JavaScript and am learning in school! There is an assignment that I am doing by creating a game but the alert keeps popping up with the wrong one. Every time it alerts as "You found a match!" for every card, however this is not supposed to happen. I have been trying to figure this out for the last hour. Thanks

var cards = ["queen", "king", "queen", "king"];

var cardsInPlay = [];

var cardOne = cards[0];

cardsInPlay.push(cardOne);

console.log("User flipped " + cardOne);

var cardTwo = cards[1];

cardsInPlay.push(cardTwo);

console.log("User flipped " + cardTwo);

if (cardsInPlay.length === 2){
    cardsInPlay[0] === cardsInPlay[1];
    alert("You found a match!");
} else {
        alert("Sorry, try again");
    }

Upvotes: 4

Views: 506

Answers (2)

MaxZoom
MaxZoom

Reputation: 7763

I think you ment to put the condition like below:

if (cardsInPlay.length === 2 && cardsInPlay[0] === cardsInPlay[1]) {
  alert("You found a match!");
}

Upvotes: 0

Brad
Brad

Reputation: 163603

You have a simple syntax error.

if (cardsInPlay.length === 2){
  cardsInPlay[0] === cardsInPlay[1];

By putting your second conditional inside the bracket {, you've made it ineffective. Try this:

if (cardsInPly.length === 2 && cardsInPlay[0] === cardsInPlay[1]) {

The condition always goes inside the parenthesis ( ). If it's outside of it, it won't work.

Typing cardsInPlay[0] === cardsInPlay[1]; when they aren't equal is effectively like typing false;. It's technically valid, but doesn't do anything.

Upvotes: 2

Related Questions