DEV Community

Discussion on: Pattern Matching in Javascript with alexmerced-patternmatcher

jonrandy profile image
Jon Randy • Edited on

This works for regex but what if you also want to check variable types, whether a key exist in an object, or the number of elements in a array, then just a big slew of ifs are your only choice.

Not really - this technique works with anything - it just compares true with the result of whatever expression you put in the case. Doesn't need to be regex. For example - testing a key is in an object:

   case 'red' in obj:
      console.log("has a red property")
   case 'blue' in obj:
      console.log("has a blue property")
   case 'green' in obj:
      console.log("has a green property")
      console.log("none of them")

Enter fullscreen mode Exit fullscreen mode

Granted - this isn't really that different to writing a bunch of ifs, but it works and could be considered more readable in some cases