Tomjesch
Tomjesch

Reputation: 510

Why does my if else statement return the incorrect result?

i have the following if else statement in my Main.js file:

var fixA = "Trap";
var fixB = "Ball";

console.log(fixA); 
console.log(fixB);

if (fixA == "Mouse" || fixA == "Ball" && fixB == "Mouse" || fixB == "Ball") {
    console.log("Ball hit mouse");
}else if (
    fixA == "Trap" || fixA == "Ball" && fixB == "Trap" || fixB == "Ball") {
    console.log("Ball hit trap"); 
}else if (
    fixA == "Trap" || fixA == "Mouse" && fixB == "Trap" || fixB == "Mouse") {
    console.log("Trap hit mouse");
}

In my original statement the fixA and fixB variables are assigned based upon the objects colliding with each other, which did not work. It kept displaying "Ball hit mouse", the result of the if().

Looking for the problem myself I gave the fixA and fixB a fixed string which again resulted in the same output. Even my first two console logs right after setting the variables log the correct strings. So there must be something wrong with the statement itself. I did some reading, research, etc but I cant seem to figure out whats wrong with it.

Could somebody help me?

Upvotes: 0

Views: 179

Answers (2)

Kos
Kos

Reputation: 72221

2 levels of mistakes here. One is operator precedence:

// your code
fixA == "Mouse" || fixA == "Ball" && fixB == "Mouse" || fixB == "Ball" 
// how it works
(fixA == "Mouse") || ((fixA == "Ball" && fixB == "Mouse") || (fixB == "Ball" ))
// what I assume you wanted
(fixA == "Mouse" || fixA == "Ball") && (fixB == "Mouse" || fixB == "Ball")

But that's still incorrect, because it will also trigger for Mouse-Mouse or Ball-Ball, not just Mouse-Ball.

You'd need a condition like:

(fixA == "Mouse" && fixB == "Ball") || (fixA == "Ball" && fixB == "Mouse")

Upvotes: 3

Gregor
Gregor

Reputation: 4434

Have a look at the operator precendece of JavaScript. The && operator binds stronger than the || operator. You can circumvent this behaviour by adding parantheses to your conditions.

if ( (fixA == "Mouse" || fixA == "Ball") && (fixB == "Mouse" || fixB == "Ball")) {
    console.log("Ball hit mouse");
}else if (
    (fixA == "Trap" || fixA == "Ball") && (fixB == "Trap" || fixB == "Ball")) {
    console.log("Ball hit trap"); 
}else if (
    (fixA == "Trap" || fixA == "Mouse") && (fixB == "Trap" || fixB == "Mouse")) {
    console.log("Trap hit mouse");
}

Upvotes: 3

Related Questions