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.
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') {
...
}
Array.includes is not supported on IE11 or Edge although a polyfill can include it.Use Array#indexOf method with an array.
if(['a','b','c','d','e'].indexOf(item) > -1){
//.........statements......
}
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)) {
...
}
ab ?ab, he'll use your answer. His example doesn't show ab so I would assume he doesn't require that functionality. kk :D
elsepart here?if('abcde'.indexof(item) >-1)...