Question: Add RegExp as `case` statement in `switch`

This might be a short discussion. Is there a reason not to add/allow a regex as a value for a case in a swtich?

function doStuff(arg) {
  switch (arg) {
    case /abc/:
      // do something
      break; // or return

    case /xyz/:
      // do something else
      break; // or return

    // other cases with other regexs

    default:
      // do other things
      break; // or return
  }
}

doStuff('abc'); // matches /abc/
doStuff('xyz'); // matches /xyz/
doStuff(undefined); // matches default (maybe)

One reason could be that this is already "in the works" as part of GitHub - tc39/proposal-pattern-matching: Pattern matching syntax for ECMAScript

It has been valid syntax since ES3, though it's useless (because case /xyz/: never matches). We can't change the semantics (theoretically possible, but very unlikely in practice). So the only option is to introduce a new feature, aka. the pattern matching proposal.

1 Like

I guess I was a little unclear. I was intending to ask about why we wouldn't want to add it as a feature in a future version. Secondly, my intention was for it to work by actually testing the pattern against the value provided in the switch(value) opening statement. So it would behave more like this:

function doStuff(arg = '') {
  switch (true) {
    case /abc/.test(arg):
      return 'hello'

    case /xyz/.test(arg):
      return 'world';

    // other cases with other regexs

    default:
      // do other things
      return 'nope.'
  }
}

doStuff('abc'); // matches /abc/
doStuff('xyz'); // matches /xyz/
doStuff(undefined); // matches default (maybe)

One reason it might not get added to switch in a future version of JavaScript is that it might be part of GitHub - tc39/proposal-pattern-matching: Pattern matching syntax for ECMAScript, which allows switch to remain as it is. And for code wanting the more advanced features they would switch to match

That's valid. I wasn't aware of match coming so thank you for that. I'll have to check it out.