0

Multiple conditions for one variable in 'if' condition.

e.g

if(x === "dog" || x === "cat" || x === "dog" || x === "lion" || x === "fish"){
  console.log('animal');
} 

else if (x === "john" || x === "micheal" || x === "daisy" || x === "smith" )
{
  console.log('people')
}

Result is true.

But I want to refactor the code like that

if(x==="john"||"micheal"||"daisy"||"smith")

How can be?

Backs
  • 24,430
  • 5
  • 58
  • 85
uSai
  • 31
  • 2
  • 7
  • 1
    If you think, what has the duplicate to do with an array, think about this: check if your value for `x` is any of the values within the collection `"john", "michael", ..."`. Then your question turns into something like "is `x` contained in that array"? – MakePeaceGreatAgain Jun 18 '18 at 10:41
  • 3
    Addition to above `["john","micheal","daisy","smith"].includes(x)` see [`Array.prototype.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – Satpal Jun 18 '18 at 10:43

0 Answers0