DEV Community

Discussion on: Pattern Matching in Javascript with alexmerced-patternmatcher

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

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:


switch(true){
   case 'red' in obj:
      console.log("has a red property")
      break
   case 'blue' in obj:
      console.log("has a blue property")
      break
   case 'green' in obj:
      console.log("has a green property")
      break
   default:
      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