2

I have code like this:

if (view == 'delete' || view =='edit' || view == 'new') {} 

Is there a more clean way that I can code this without using an external library. It just does not look too good to have all the || and maybe more later.

2 Answers2

3

Use indexOf (won't work on ancient IE versions):

if (["delete", "edit", "new"].indexOf( view ) >= 0) { alert("ME");}
Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
  • This is not any way cleaner or easier to understand than what OP has written. If anything other than using `===` instead of `==` his or her way of writing it is much cleaner and expressive. – rdodev Nov 30 '13 at 02:39
  • 2
    @rdodev, its a matter of opinion. I come across this compacted expression shorthand in js very often, and I personally use it and like it. – goat Nov 30 '13 at 02:40
  • 2
    indexOf support http://kangax.github.io/es5-compat-table/#Array.prototype.indexOf – Jonathan de M. Nov 30 '13 at 02:44
  • @rambocoder it's also less efficient as it will check all possibilities for index, whereas the original boolean form has short-circuit once a match has been found. http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html#the_fastest_conditionals – rdodev Nov 30 '13 at 02:45
  • @rdodev indexof() will absolutely stop searching after finding a match. Regardless, I, and many others place a relatively high value on readable and concise code, and a relatively low value on unwarranted micro optimizations. – goat Nov 30 '13 at 03:06
  • I'd be really really amazed if any major browser implemented an `indexOf` that doesn't stop at the very first match. – Maurício Linhares Nov 30 '13 at 03:10
1

You can also use regular expression:

if (/^(delete|edit|new)$/.test(view)) {
    // true
}
bagonyi
  • 3,258
  • 2
  • 22
  • 20