Skip to content Skip to sidebar Skip to footer

Javascript Logical Operators - And Vs. Or

I'm relatively new to Javascript and programming in general. Today while writing a simple triple dice roll simulator I struck a problem that I worked around but which I still don't

Solution 1:

You can use either OR or AND, they can be transformed from one to another with De Morgan's Laws.

dice1!=dice2||dice2!=dice3

is equivalent to:

! (dice1 == dice2 && dice2 == dice3)

The first expression says "while the first two dice are not equal OR the second two dice are not equal" (i.e. one of the two equalities is false).

The second expressions says "while NOT (the first two dice are equal AND the second two dice are equal)" (i.e. one of the two equalities is false).

It's helpful to use a truth table for this kind of stuff, it can help you visualise the boolean combinations.

As for your side note, the random number generation, you're doing it the right way. You need to get a new number each time so you have to call Math.random() again each time.

You could extract that into a function so it's cleaner when you want to use it:

functiongenerateRandom(diceSides) {
    returnMath.floor(Math.random() * diceSides + 1);
}

and then use it like so:

var diceOne = generateRandom(diceSides);

Solution 2:

Your understanding of the logical operators is correct, you're confused about how while works. When the condition is met it keeps looping, it stops when the condition fails.

So when only two of the dice are equal, one of the != conditions will be true, so the || condition is also true, so it continues to loop. When all three dice are equal, both != conditions will be false, and false || false is also false, so the loop stops.

Some languages have an until statement, which is like while but inverts the condition so that the loop stops when the condition is true. That would work the way you were describing.

Post a Comment for "Javascript Logical Operators - And Vs. Or"