-5

I have a very basic statement that isnt outputting the correct value but I cant get my head around why.

My variable has the following value:

var bedroomNums = "0_1"

Yet this output displays as true in Chrome console:

bedroomNums != ("0_0" || "0_1" || "0_2")

I am trying to create an IF statement to say:

if bedroomNums doesnt equal X or Y or Z then the statement is true

I have tried:

bedroomNums != "0_0" || bedroomNums != "0_1" || bedroomNums != "0_2"

but this also displays true

Where am I going wrong

  • 4
    I think what you seem to be actually looking for is not a logical `OR`, but a logical `AND` (meets *every* condition). – esqew Feb 09 '21 at 21:22
  • `bedroomNums` cannot be three different values at the same time. If it equals "0_0", then by necessity it *won't* equal "0_1", so at least two of those ***or*** conditions must be true. – deceze Feb 09 '21 at 21:22
  • `bedroomNums != "0_0" && bedroomNums != "0_1" && bedroomNums != "0_2"` – Nick Feb 09 '21 at 21:23
  • Would this still work in parentheses `bedroomNum != ("0_0" && "0_1" && "0_2")`? IM not even sure if that is correct syntax – Anthony Broadbent Feb 09 '21 at 21:27
  • 1
    it's not the correct syntax for what you are seeking to do. Each expression needs to compare `bedroomNum` (i.e. `( bedroomNums != "0_0" && bedroomNums != "0_1" && bedroomNums != "0_2")` – blurfus Feb 09 '21 at 21:28
  • 2
    @AnthonyBroadbent What you've provided in your comment is technically valid ECMAScript syntax, but won't work the way you think it will. String values are "[truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)", so `"0_0" && "0_1" && "0_2"` is actually `true && true && true`. Dependent on the type and value of `bedroomNums`, it's likely this comparison would *not* return the result you are expecting or need. – esqew Feb 09 '21 at 21:29

1 Answers1

1

What you're actually looking for is a logical AND, which would ensure that every condition is met:

if (bedroomNums != "0_0" && bedroomNums != "0_1" && bedroomNums != "0_2") {
    // `bedroomNums` is not one of "0_0", "0_1", "0_2"
}

If one of these checks returns FALSE (that is, bedroomNums is set to one of these values), the code inside the curly braces will not be executed.


An alternative way to express this same condition would be to enumerate each of these values you're comparing against into an Array structure, then checking to ensure that the value of bedroomNums isn't present in said Array using Array.prototype.includes():

if (!["0_0", "0_1", "0_2"].includes(bedroomNums)) {
    // `bedroomNums` is not one of "0_0", "0_1", "0_2"
}

This style is generally more helpful in situations where your program has to enumerate all possible values for a condition dynamically (based on some other logic or data source).

esqew
  • 42,425
  • 27
  • 92
  • 132