1

I have a condition:

if (item == 'a' || item == 'b' || item == 'c' || item == 'd' || item == 'e') {
    // statements
}

How can I reduce the branching? Is there any other way to write this in JavaScript.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
abhit
  • 973
  • 3
  • 17
  • 40

4 Answers4

7

You can also use the newer Array.includes

if (['a','b','c','d','e'].includes(item)) {
  ...
}

Another option (for the very specific case you posted) would be to compare unicode point values using </>

if (item >= 'a' && item <= 'e') {
   ...
}
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • 1
    Word of caution, `Array.includes` is not supported on [IE11 or Edge](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility) although a [polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill) can include it. – tresf Sep 01 '16 at 05:27
  • @QZSupport Array.includes is actually [supported in Edge](https://developer.microsoft.com/en-us/microsoft-edge/platform/status/arrayprototypeincludeses2016/?q=includes) (not in IE11 though). Thanks for noting that! :) – Rob M. Sep 01 '16 at 05:30
  • thanks, [updated](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility). – tresf Sep 01 '16 at 05:37
5

Use Array#indexOf method with an array.

if(['a','b','c','d','e'].indexOf(item) > -1){
   //.........statements......
}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
3

You can use an array as shown below.

var arr = ['a','b','c','d','e'];
if(arr.indexOf(item) > -1) 
{
   //statements
}
Nikhilesh K V
  • 1,480
  • 13
  • 20
2

This would work nicely:

if('abcde'.indexOf(item) > -1) {
    ...
}

You could also use the newer String.prototype.includes(), supported in ES6.

if('abcde'.includes(item)) {
    ...
} 
Max
  • 2,710
  • 1
  • 23
  • 34