Logo

Today I Learned

Pseudo pattern matching in JavaScript

One of my favourite parts of Elixir is pattern matching. Here’s an example:

elixir
1def weather_advisory(temperature) when temperature >= 100 do
2  "Scorching hot! Stay hydrated and find shade."
3end
4
5def weather_advisory(temperature) when temperature >= 50 do
6  "Pleasant weather. Enjoy the day!"
7end
8
9def weather_advisory(_temperature) do
10 "Chilly. Grab a jacket before going out."
11end

By inverting a switch statement it’s possible to implement something similar in Javascript:

javascript
1function weatherAdvisory(temperature) {
2  switch(true) {
3    case temperature >= 100:
4      return "Scorching hot! Stay hydrated and find shade."
5
6    case temperature >= 50:
7      return "Pleasant weather. Enjoy the day!"
8
9    default:
10      return "Chilly. Grab a jacket before going out."
11  }
12}

While this is a relatively simple use-case and could be replaced with if/else blocks, I’ve found this approach to provide better clarity of the conditional logic.