← Back to Cheatsheets

The Inverted Switch Pattern in Javascript

A normal switch can look like this

1switch (color) {
2 case "red":
3 return "apple"
4 case "yellow":
5 return "banana"
6 default:
7 return null
8}
9

The inverted switch looks like this

1switch (true) {
2 case color === "red":
3 return "apple"
4 case color === "yellow":
5 return "banana"
6}
7

This is similar to a series of inline if statements

1if (color === "red") return "apple"
2
3if (color === "yellow") return "banana"
4

For if statements to span multiple expressions, they need enclosing braces

1if (color === "red") {
2 const apple = getApple()
3 apple.shape = "round"
4
5 return apple
6}
7
8if (color === "yellow") {
9 const banana = getBanana()
10 banana.shape = "banana-shape?"
11
12 return banana
13}
14

But switch statements can increase in complexity without additional syntax

1switch (true) {
2 case color === "red":
3 const apple = getApple()
4 apple.shape = "round"
5
6 return apple
7
8 case color === "yellow":
9 const banana = getBanana()
10 banana.shape = "banana-shape?"
11
12 return banana
13}
14

To handle OR conditions, if statements require the || operator

1if (color === 'red' || color === 'green')
2

Switches have a fall-through feature where they continue if there is no return or break keyword, so multiple OR cases can share a single execution block. In this example, both red and green will return an apple.

1switch (true) {
2 case color === "red":
3 case color === "green":
4 const apple = getApple()
5
6 return apple
7
8 case color === "yellow":
9 const banana = getBanana()
10 banana.shape = "banana-shape?"
11
12 return banana
13}
14

References

https://kyleshevlin.com/pattern-matching