Home > Blockchain >  if statement with multiple or conditions returning wrong value
if statement with multiple or conditions returning wrong value

Time:12-26

I am pretty sure I am missing something basic here but I am having trouble with using multiple or or || operators with my if statement.

For some reason the if statement is not catching the name variable:

testword = "billy"

if ((testword != "billy") ||
    (testword != "tom") ||
    (testword != "sara") ||
    (testword != "michael")) {
console.log("none of the names match")
} else {
console.log("name found!")
}

When I try this I get none of the names match when I should get name found!

CodePudding user response:

Your logic is a bit convoluted

A far simpler approach to both write and understand is put all those names in an array and see if the array includes the testword. This is only a single boolean test

const testword = "billy",
  words = ["billy", "tom", "sara", "michael"]

if (words.includes(testword)) {
  console.log("name found!")
} else {
  console.log("none of the names match")
}

CodePudding user response:

The or operators execute to true when any of the condition is not equal to testword thus logging none of the names match

However, you can try to change your code to

testword = "billy"
names = ['billy','tom','sara','michael',]

if (names.indexOf(testword) != -1) {
console.log("name found!")
} else {
console.log("none of the names match")
}
  • Related