Embracing pattern matching in JavaScript

Apartment window pattern

If-else and switch-case are easily the most common code that we write everyday. It’s easy to write and understand, as long as we keep the checks simple and shallow. But the real world is not always a happy-go-merry place. Every now and then we are challenged with problems that force us to write complex or worse, nested checks.

Anything beyond a shallow check is bound to fail, bound to allow bugs to creep in. And in general, it’s irksome to read and review deep nested if-else and switch-case. The nested structure ultimately buries the original intended functionality.

Let’s take a quick look at a simple example. Here the problem to be solved is to return an icon component for particular menu title:

This seems quite straight forward. You can send in the icon title and get the (SVG) icon component to be rendered. Now, for a real application this file can grow real quick. Adding a new icon, means adding a new case. Not to mention this would be done by multiple team members. Try and imagine this function returning tens of matching icons. The code will be huge. On top of that, if we want to return icons dynamically, the code only gets more complex.

Let’s take a closer look at what we do when add a new icon. Beside the repetitive case code, what is the unique thing that we are adding? A pattern relationship, connecting, X title to Y component. Keeping that in mind, let’s take a different approach to solve the same problem:

This is a much better way to keep the pattern and the matching part separate. iconList is just an object containing the patterns. The matching part is fully decoupled and unaware of the actual patterns. To add a new icon, we just need to add a new key: value pattern. This kind of approach also makes dynamic pattern matching easier. Take a look at the following example:

In the above example, for settings, based on user type, we are dynamically sending either <AdminSettings /> or <Settings />. We achieve this by using a method pattern as the output generator. The matching part checks and executes any function values before returning.

I know, I know I haven’t shown an example with if-else. Here is a sample from an actual live application:

We can truly code without ever using deeply nested conditional statements by embracing pattern matching. We just barely scratched the surface. There’s much more we can do with this concept.


PS: I’m fairly new to functional programming. If you find any improvements, you are more than welcome to correct me 😁.