What’s wrong with the switch statement in JavaScript?

Some alternative remedies to the (mostly) problematic switch/case statement

Orlando La
tandemly
Published in
5 min readSep 7, 2017

--

As an enthusiast and long time community member I believe we are neglecting the review of JavaScript’s fundamentals. Below I present one of the many, many, many takes on the pitfalls of the switch statement as is and why it is in need of serious review by the community to keep JavaScript competitive with other languages enabled by WebAssembly; and in addition solutions, temporary and permanent, that can bypass its inflexibility.

Ill suited for an evolution

In today’s age, many libraries and patterns leverage the switch statement to represent states or operations to be performed should a matching case prevail. This particular method can be easily recognized by functional programming connoisseurs and experts alike as “pattern matching”, whereas one or more inputs are mapped to proper outputs that come about as the result of a state passed in.

In theory, the switch case statement has the capacity to fulfill the objectives of pattern matching (mapping a series of states and input to an output); but it is more realistic to say that by default library authors see no other alternative but to begrudgingly employ it as they see no other mature pattern or language feature fit for the task.

Pitfalls

To a certain degree, the switch/case mechanism is a potentially hazardous syntax to represent states of modern applications. Each case statement grants a license to perform a plethora of jigsaw operations, patching together logic that skips out on the whole paradigm of pattern matching, particularly:

  • The statement can make calls in one case, and in others, mutate or apply transforms to data in another.
  • In another scenario, one statement could stop a loop in the above statements, while in other cases manipulate data or do nothing at all.
  • Due to its inability to resolve to a value, it implicitly encourages using variables and/or other hard to trace methods to communicate the output as a result
  • There is no explicit one-to-one, input to output mapping guaranteed with the statement, one must hope that an author strictly adheres to the methodology in their implementation.
Some of the pitfalls of switch statement

Some of these pitfalls, may not seem inherently malignant to users, however its advertised utility comes with large disclaimers, most of which forcibly limit the power of a program at any point where the statement is employed. On top of these difficulties, that can be introduced by lack of consistency, there are a whole class of errors and bugs that can be introduced from simply using the statement, including:

  • Misaligned fallthrough cases
  • Multiple cases can run, making it harder to trace logic
  • Withholding the default case, which makes the pattern dubious and confusing for new language consumers.
  • Hosting any other conditionals (or even another switch statement) inside a case makes the program much more harder to follow
  • Lastly, you can only match a case to very narrow value. Combinations of values, computed values, applied reflection and anything else must be primitively reduced to a single value. Making many programs that reach a certain complexity look elsewhere, or worse, adding a layer of mind bending conditionals and/or operations within a case.
Implementing a case as a funciton aren’t usually found in most apps. Extract complex patterns with it definitely feel wrong.

The growing pains of using the switch statement have most definitely been experienced by many seasoned programmers and yet it is all too easy to accept the status quo. If we are to look into the future, we must envision some alternatives that can help bypass its structural difficulties.

Alternative one: ES6 Collections

One alternative I promote is to use maps and sets, but to be clear this isn’t a comprehensive solution. A collection (Map or Set) plus a function or two works much better for the majority of use cases and allows the programmer to remain flexible and add additional logic and complexity as they go.

What’s so special about collections?

Not much. And a lot.

A simple collection representing pizza sizes

There are lots of benefits working with a collection over a switch statement. For one, each input is mapped to a predictable output, either you’ll get some data or you won’t. Calling the .get() or .has() function of a map or set, respectively, will not result in indirectly triggering operations. Another benefit is that they can be properly typed either with Flow or TypeScript, errors are explicit when there is an invalid case. Additionally, using collections also help programmers easily conform to increasingly popular functional programming patterns.

Collections, while not a panacea, work well for existing applications where one needs to translate an input to a raw value (strings, objects, etc).

Second alternative: Leave as is

This article is by no means dictating that we must abandon all switch statements, but to highlight its serious limitations in its emergent usage and open a broader discussion. The community doesn't just have to stop at building great apps as is today, we all benefit from improving the tools and patterns supported in the language.

One can agree with the premises of this article and still use switch statements happily; after all they work fine for the majority of applications as is. However, if we are to look towards the future, we can’t rely on what has worked in the past but continually evaluate all aspects of the language. We have to be continually sharpening our tools, which leads into my next and final proposed alternative:

Third alternative: Support the pattern matching proposal

There’s a pattern matching proposal from Brian Terlson of Microsft (who also introduced async/await into JavaScript) on the horizion. I see no reason that JavaScript’s language development can’t benefit from evolutions made in other languages like C#, Swift, and Java. In fact, adopting approaches to problem solving that certain languages solve does our community a great favor.

I think that there’s a good chance that we will be seeing the addition of a pattern matching feature in JavaScript in the future. Of course, with a new language feature, an explosion of new libraries and patterns that add conciseness, clarity, and correctness that help keep JavaScript competitive and productive, and hopefully an obvious choice to develop web apps in for a long time to come.

--

--