Reputation: 15
I'm working on a calculator app and I have given each button a value corresponding to their numbers or characters.
I have an if condition that's supposed to check if the user clicks any button other than "C" or "del" (delete) button. If they do click the "C" or "del" button, no value is added to neither the userInput nor the display.
The problem I'm having is that even when I click "C" and "del", the if statement would still execute.
let userInput = '';
const display = document.querySelector('.display');
const buttons = document.querySelectorAll('input[type="button"]');
for (let button of buttons) {
const value = button.value;
if (value !== "C" || value !== "del"){
button.addEventListener("click", function(){
userInput+=value;
display.innerHTML += value;
console.log(button.value);
});
}
}
Upvotes: 0
Views: 200
Reputation: 29002
It's easy to see what's happening if we write out the boolean truth table here:
+----------+------------------+--------------------+--------+
| value | value != "C" (A) | value != "del" (B) | A || B |
+----------+------------------+--------------------+--------+
| "C" | false | true | true |
| "del" | true | false | true |
| "banana" | true | true | true |
+----------+------------------+--------------------+--------+
The only way for this to be false
is if both the A and B condition are false
, however that will require value
to be both "C"
and "del"
at the same time. Which is not possible for strings. Thus, because logical OR is used, the output will always be true
regardless of input.
Instead, using logical AND is what you actually want to accomplish:
+----------+------------------+--------------------+--------+
| value | value != "C" (A) | value != "del" (B) | A && B |
+----------+------------------+--------------------+--------+
| "C" | false | true | false |
| "del" | true | false | false |
| "banana" | true | true | true |
+----------+------------------+--------------------+--------+
Upvotes: 0
Reputation: 13902
I think people have made it pretty clear already that the way you've made your if-statement, it will ALWAYS come out as true, because it will always either be true that it's not 'C', OR it's not 'del'.
However, I thought I'd add another approach: using an array, and using the array.includes
function
const badValues = ['C', 'del'];
if (badValues.includes(value)) {
// value is either C or del
} else {
// value is not C or del
}
Upvotes: 0
Reputation: 386654
You need an logical AND &&
operator, because both condition have to be true.
value !== "C" && value !== "del"
Upvotes: 1
Reputation: 591
You need to use AND operator, because it should not be 'C' and 'del'
value != "C" && value != "del"
Upvotes: 2