All know roblems with switch, so let’s refactor and setup a simple Object literal that returns a String value only:
We’ve saved a few lines of code from the switch, and to me the data is a lot cleaner in presentation. We can even simplify it further, without a default case:
We might, however, need more complex code than a String, which could hang inside a function. For sake of brevity and easy to understand examples, I’ll just return the above strings from the newly created function:
This wraps the two Object lookups inside parenthesis ( ), treating them as an expression. The result of the expression is then invoked. If drinks[type] isn’t found in the lookup, it’ll default to drinks['default'], simple!
We don’t have to always return inside the function either, we can change references to any variable then return it:
Object Literal “fall through”
With switch cases, we can let them fall through (which means more than one case can apply to a specific piece of code):
We let coke and pepsi “fall through” by not adding a break statement. Doing this for Object Literals is simple and more declarative - as well as being less prone to error. Our code suddenly becomes much more structured, readable and reusable: