if statement - How to correctly chain OR and AND conditions in Javascript? - Stack Overflow

admin2025-04-19  0

I am trying to write

if (x !== "One" || x !== "Two" || x !== "Three") {
   x = undefined;
}

However, this is not working for me. What is the correct way to get the same result?

It works fine when I only have one condition

if (x !== "One") {
   x = undefined;
}

I am trying to write

if (x !== "One" || x !== "Two" || x !== "Three") {
   x = undefined;
}

However, this is not working for me. What is the correct way to get the same result?

It works fine when I only have one condition

if (x !== "One") {
   x = undefined;
}
Share Improve this question edited Aug 20, 2014 at 20:39 stcho asked Aug 20, 2014 at 19:24 stchostcho 2,1693 gold badges31 silver badges45 bronze badges 3
  • 6 Why are you trying to set a variable called var to something? var is a keyword? – scrblnrd3 Commented Aug 20, 2014 at 19:25
  • Can you explain, in words, when you want the if statement to run? When it's none of these? P.S. You can't name a variable var. – gen_Eric Commented Aug 20, 2014 at 19:26
  • 1 You probably want if(!(var == 'One' || var == 'Two')), which by DeMorgan's Law is if(var != 'One' && var != 'Two'). You can also simplify this by using an array if(['One', 'Two'].indexOf(var) === -1). – gen_Eric Commented Aug 20, 2014 at 19:28
Add a ment  | 

1 Answer 1

Reset to default 6

You wanted an and, not an or. And your variable name can't be var.

var t = "One";
if (t !== "One" && t !== "Two" && t !== "Three") {
  t = undefined;
}

Because the previous or(s) would always evaluate to true. if the variable was "a" or var was "One" it's not "Two" or "Three".

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745075311a283532.html

最新回复(0)