JavaScript Tip: Replace Switch Statements With Object Literals
I'm not a big fan of JavaScript's switch
statement. Its syntax is hard to remember and can cause tricky bugs if you forget to add a break
statement for every case.
Let's take a look at an example:
I prefer using JavaScript's object literals over switch
statements as the code is faster, more readable, and less verbose.
For each case we would have in the switch
statement, we need to define an object key for each case:
Finally, let's handle the default
case of the switch
statement by adding a default key:
We try to access the value using rolesMap[id]
and use the nullish coalescing operator (??
) to set the default value if the value is undefined
or null
.
If you liked this tip, follow me on Twitter to get notified about new tips, blog posts, and more.
JavaScript Tip: Get Valuable Info About Device Battery
TODO
JavaScript Tip: Return Object Literal From an Arrow Function
How to return an object literal from an expression-bodied arrow function as introduced by ECMAScript 2015.