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 null8}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"23if (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"45 return apple6}78if (color === "yellow") {9 const banana = getBanana()10 banana.shape = "banana-shape?"1112 return banana13}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"56 return apple78 case color === "yellow":9 const banana = getBanana()10 banana.shape = "banana-shape?"1112 return banana13}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()56 return apple78 case color === "yellow":9 const banana = getBanana()10 banana.shape = "banana-shape?"1112 return banana13}14