Action pattern-matching: A use-case for switch(true)

Lars Holdaas
2 min readDec 2, 2020
Photo by Antoine Dautry on Unsplash

switch(true) is pretty much the Psyduck of Javascript; the first time you encounter it in the wild, it immediately confuses you; and it’s super effective!

But why!?

is probably what you thought when you figured out what it was doing, opting instead to use if-else clauses. I agree that it’s probably a usually better idea, but I’d like to introduce one case that definitely fits better with switch(true):

Pattern-matching action types in Redux reducers!

So this technique can be used to update the state according to action type patterns rather than matching the action type string to set values!

But why!?

is probably what you’re thinking right now! Don’t worry, I’ve prepared the Full Heal so we can rid you of the confusion once and for all. So let’s look at the specific use-case.

HttpReducer

Assume we’re using some Redux middleware (thunk/saga/redux-observables etc.) for handling API interactions. In this example we’ll assume we have a reducer that keeps track of the requests, success and failure actions that are fired, and that they’re all using the postfixes :REQUEST, :SUCCESS & :FAILURE respectively.

--

--

Lars Holdaas

Web developer working in Japan. Passionate about maintanability and clean coding.