Rewriting Javascript : Replacing the Switch Statement

Chris Burgin
Spark
Published in
4 min readApr 17, 2017
TLDR; See Banner Image.

The humble switch statement, it exists in almost every programing language and javascript is no exception. The switch statement allows for cleaner organization of code when a large number of evaluations needs to be made. But the switch poses several problems, which I think are best shown through an example.

The Problem

Below we see a standard switch statement wrapped in a function. This statement will return a fact about our desired dog breed (Border Collie Fan Club).

const dogSwitch = (breed) => {
switch(breed) {
case("border"):
return "Border Collies are good boys and girls."
break;
case("pitbull"):
return "Pit Bulls are good boys and girls."
break;
case("german"):
return "German Shepherds are good boys and girls."
break;
}
}
dogSwitch("border") // "Border Collies are good boys and girls."

As you can see this code is simple and gets the job done, but has problems that make it a non-ideal solution in many cases.

1. Non Standard Syntax

Due to how a switch functions we must include the {} brackets around the block of our function. Whenever possible in ES6 I attempt to leave the brackets off. This is a fairly standard syntax in ES6, an example of this syntax is below using arrow functions.

// returns `hi {name}`
const sayHi = (name) =>
`Hi ${name}!!`
sayHi("Chris") // output: Hi Chris!

Notice there are no brackets! Now to be fair this new syntax only supports the ability to return one value, but in functional programing thats best. Sadly using the switch statement does not allow us to take full advantage of the new ES6 syntax. (booooo!! 👻)

2. Error Prone

Switch statements, with their non standard syntax included, are difficult to read and contain extra “syntactical sugar (not good sugar)” that we really don’t want to be reading.

When code is more difficult to read it becomes more likely that errors will be introduced over time as your code scales. With a switch statement its easy to leave off a simple break which can result in the default case being executed. This can be seen below.

switch("first") {
case("first"):
console.log("First Case")
default:
console.log("Default Case")
}

A simple mistake to make, but a mistake that can be incredibly hard to debug in a much large switch statement.

The Solution

Object Literals. Instead of using the switch statement we can use an object literal to replicate the functionality of a switch while reducing the negative side affects inherent in the switch statement. First let us look at an example.

const dogSwitch = (breed) => ({
"border": "Border Collies are good boys and girls.",
"pitbull": "Pit Bulls are good boys and girls.",
"german": "German Shepherds are good boys and girls."
})[breed]
dogSwitch("border") // "Border Collies are good boys and girls."

So what is going on here? We have create a JSON object that contains our cases as key values in the object. Next we pass in the value we want to select from out object. Very similar to how the following simple example works when selecting from a JSON Object.

const jsonObject = {
"i1": "item 1",
"i2": "item 2"
}
jsonObject["i1"] // "Item 1

The first thing to note in our new object literal switch is that we have removed {} brackets and consequently we removed the return statements. This allows us to follow a cleaner more functional ES6 syntax. Additionally by using object literals all of the non standard “syntactical sugar” has been removed, simplifying code and increasing readability.

Performance for switch/if statements can be a concern when the number of cases becomes large. With a smaller number of cases a switch is the faster option, while when the number of cases grows a single lookup in a object literal becomes the faster option. In this use case I am not incredibility concerned with performance, more so readability.

A Complex Example

Lets say for example that you are currently using a switch statement for your Redux Store. The following example will show you how to implement your Redux store using an object literal switch.

Redux Store Reducers with Object Literals

I wont go into to much detail on this code as I believe the breakdown of the simple example above explains how this redux store will work. Just note the lack of a switch statement and the increased readability of our code.

Conclusion

The switch statement is a staple of many programing languages but has many inherent problems that can be solved by implementing an object literal solution instead. This does not mean that there are no uses for the switch statement or that object literals is always the right answer. Instead object literals as switches should become another tool in your javascript tool belt.

Thanks! 💚

Thanks for taking the time to read this article! I appreciate and value every recommend, comment (nice or mean), and follow! I’ll be covering more topics in the near future about rewriting basic Javascript concepts using the new standards.

Useful Reading

The following are some useful readings based of off topics covered in this article.

--

--

Chris Burgin
Spark
Editor for

Christ follower. Dog caretaker. Developer at Generation Tux.