stevef
stevef

Reputation: 1

JS nested if statement logic not working as intended

function decideWinner() {

comChoice = generateComputerChoice();
userChoice = "Rock";

    if (userChoice === comChoice) {
        console.log("game drew");
    } else {
        if (userChoice === "Rock" && comChoice === ("Scissor" || "Lizard")) {
            console.log("you win")
        } else if (userChoice === "Paper" && comChoice === "Rock" || "Spock") {
            console.log("you win")
        } else if (userChoice === "Scissors" && comChoice === "Paper" || "Lizard") {
            console.log("you win")

        } else if (userChoice === "Lizard" && comChoice === "Spock" || "Paper") {
            console.log("you win")

        } else if (userChoice === "Spock" && comChoice === "Scissor" || "Rock") {
            console.log("you win")

        } else {
            console.log("you lose")
        }
    }
}
decideWinner()

The comChoice is generated from another function. userChoice is set to "Rock" first part should return draw if both are the same and 2nd returns a win or loss depending on the outcome of the comChoice. But this is not happening i am getting a draw if "Spock" is drawn by the computer and a win in all other circumstances. can anyone see what ive done wrong please ?

Upvotes: 0

Views: 39

Answers (2)

Michael
Michael

Reputation: 1674

One problem that I notice is with your OR operator. Checking comChoice === "Rock" || "Spock" is not doing what you expect.

instead you need to check it like this: (comChoice === "Rock" || comChoice === "Spock")

On another note I would just use == instead of === in your case since we can't see what data type is being passed which could result in false results.

Upvotes: 1

lanxion
lanxion

Reputation: 1430

The problem is with how you are using the OR(||) operator.

Using val1 || val2 returns the value of the first one that is truth. So, essentially ("Scissor" || "Lizard") will return "Scissor" everytime. What you instead intend to do is to actually check equality with comChoice, so you should refactor your code as such:

if (userChoice === comChoice) {
    console.log("game drew");
} else {
    if (userChoice === "Rock" && (comChoice === "Scissor" || comChoice === "Lizard")) {
        console.log("you win")
    } else if (userChoice === "Paper" && (comChoice === "Rock" || comChoice === "Spock")) {
        console.log("you win")
    } else if (userChoice === "Scissors" && (comChoice === "Paper" || comChoice === "Lizard")) {
        console.log("you win")
    } else if (userChoice === "Lizard" && (comChoice === "Spock" || comChoice === "Paper")) {
        console.log("you win")
    } else if (userChoice === "Spock" && (comChoice === "Scissor" || comChoice === "Rock")) {
        console.log("you win")
    } else {
        console.log("you lose")
    }
}

Upvotes: 2

Related Questions