Skip to content
Advertisement

if statement with multiple or conditions returning wrong value

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!

Advertisement

Answer

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")
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement