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.

6
  • What do you mean by branching? Commented Sep 1, 2016 at 5:08
  • What's else part here? Commented Sep 1, 2016 at 5:09
  • Can use switch. developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Sep 1, 2016 at 5:09
  • sorry....updated the question. Commented Sep 1, 2016 at 5:09
  • if('abcde'.indexof(item) >-1)... Commented Sep 1, 2016 at 5:10

4 Answers 4

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') {
   ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

Word of caution, Array.includes is not supported on IE11 or Edge although a polyfill can include it.
@QZSupport Array.includes is actually supported in Edge (not in IE11 though). Thanks for noting that! :)
thanks, updated.
5

Use Array#indexOf method with an array.

if(['a','b','c','d','e'].indexOf(item) > -1){
   //.........statements......
}

1 Comment

It does reduce the code length but not the branching at all.
3

You can use an array as shown below.

var arr = ['a','b','c','d','e'];
if(arr.indexOf(item) > -1) 
{
   //statements
}

Comments

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)) {
    ...
} 

2 Comments

if item is ab ?
@PranavCBalan If it's ab, he'll use your answer. His example doesn't show ab so I would assume he doesn't require that functionality. kk :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.