Skip to main content
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Determine if string is in list in JavaScript

In SQL we can see if a string is in a list like so:

Column IN ('a', 'b', 'c')

What's a good way to do this in JavaScript? It's so clunky to do this:

if (expression1 || expression2 || str === 'a' || str === 'b' || str === 'c') {
   // do something
}

And I'm not sure about the performance or clarity of this:

if (expression1 || expression2 || {a:1, b:1, c:1}[str]) {
   // do something
}

Or one could use the switch function:

var str = 'a',
   flag = false;

switch (str) {
   case 'a':
   case 'b':
   case 'c':
      flag = true;
   default:
}

if (expression1 || expression2 || flag) {
   // do something
}

But that is a horrible mess. Any ideas?

In this case, I have to use Internet Explorer 7 as it's for a corporate intranet page. So ['a', 'b', 'c'].indexOf(str) !== -1 won't work natively without some syntax sugar.

Answer*

Cancel
3
  • 4
    This will fail on older browsers.
    epascarello
    –  epascarello
    2010-03-12 02:25:55 +00:00
    Commented Mar 12, 2010 at 2:25
  • 1
    Oops... mentioning that this doesn't work in IE would have been nice. :)
    ErikE
    –  ErikE
    2010-03-12 02:26:47 +00:00
    Commented Mar 12, 2010 at 2:26
  • 2
    @epascarello: Not only in older browsers, it will fail on any IE, even in IE8 :(
    Christian C. Salvadó
    –  Christian C. Salvadó
    2010-03-12 02:27:17 +00:00
    Commented Mar 12, 2010 at 2:27

Morty Proxy This is a proxified and sanitized view of the page, visit original site.