This has got me stumped. I'm creating a simple function that generates a random number between 1 and 6 when an element is clicked (a dice roll).
I want to use an if statement to do something if the number rolled is not a 1 or if the previous number rolled is not a 6, eg:
if(dice !== 1 || lastRoll !== 6) { //Do something
However, I cannot seem to get the OR condition working here. Both dice !== 1 and lastRoll !== 6 work fine independantly, but when combined with the OR condition in one if statement neither work.
My complete function is as such:
var lastRoll = 0;
document.querySelector('.btn-roll').addEventListener('click', function() {
var dice = Math.floor(Math.random() * 6) + 1;
console.log('current ' + dice + ' last ' + lastRoll); //<-- This displays expected results
if(dice !== 1 || lastRoll !== 6) {
lastRoll = dice;
console.log('success');
}
else {
lastRoll = 0;
console.log('fail');
}
}
Would anyone know why the OR condition doesn't work?
UPDATE:
To test I did this:
var hardCoded = 6;
if(dice !== 1 || hardCoded !== 6) {
So I expect the condition to always fail. But it doesn't. It still doesn't like the if statement.
if(dice !== 1 || lastRoll !== 6)condition it logs success every time since it 6 passes with the 1st condition and 1 passes with the second condition. I think you need AND here.if(dice !== 1 && lastRoll !== 6)hardcodedis 6, if thediceis not 1, it doesn't even check for the second condition since it is an OR and the first condition passes. It checks thehardcodedvalue only if thedicevalue is 1. You can't expect it to be failed.