0

I am using below logic for checking particular string matching with other string or not

if (searchTxt == "All" || searchTxt == "WORD1" || searchTxt == 'WORD2' || searchTxt == 'WORD3' || searchTxt == 'WORD4' || searchTxt == 'WORD5') {
}

Above code is working fine but showing warning

Reduce the number of conditional operators (5) used in the expression (maximum allowed 3)

.

How to resolve this warning

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
  • 2
    Create an array of those words and use `if(array.includes(searchTxt)){...}` – adiga Apr 05 '19 at 10:15
  • 2
    Possible duplicate of [Check variable equality against a list of values](https://stackoverflow.com/questions/4728144/check-variable-equality-against-a-list-of-values) and [Javascript: The prettiest way to compare one value against multiple values](https://stackoverflow.com/questions/9121395) and [Concise way to compare against multiple values](https://stackoverflow.com/questions/13737091) – adiga Apr 05 '19 at 10:16

2 Answers2

-1

In this example, you'd be better off with a switch statement; If you want to do the same thing with multiple terms, such as "WORD1" and "WORD2", eliminate the break and put the code you want to do in the last of the matches.

switch(searchTxt){
  case "All": 
    // do something
  case "WORD1": 
    // do something
  case "WORD2": 
    // do something
  case "WORD3": 
    // this switch case will do something for 
    // "WORD1", "WORD2", "WORD3", "All"
    break;
  case "WORD4":
    // do something
    break;
  case "WORD5":
    // do something
    break;
  default:
    // do something if no match
}
Lewis
  • 3,479
  • 25
  • 40
-2

Your code is currently needlessly repetitive.

How aout putting the acceptable options in an array then using a dynamic REGEX to test:

let allowed = ['foo', 'bar', 'etc'];
if (new RegExp('/^('+allowed.join('|')+')$/').test(searchTxt)) { alert('match'); }
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • Compare your code with something like ['foo', 'bar', 'etc'].indexOf(searchTxt) === -1 in terms of readability, performance and simplicity. – Petr Averyanov Apr 05 '19 at 10:23
  • True - `indexOf()` or `includes()` is more readable, but I still answered the question and solved the OP's problem. – Mitya Apr 05 '19 at 10:26