Javascript is required
Mokkapps LogoMichael Hoffmann

JavaScript Tip: Replace Switch Statements With Object Literals

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Jan 16, 2023
1 min read
|
18 views
Javascript
JavaScript Tip: Replace Switch Statements With Object Literals Image

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:

index.js
const getRole = (id) => {  switch (id) {    case 11:      return 'ADMIN'    case 22:      return 'OPERATOR'    default:      return 'USER'  }}

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:

index.js
const getRole = (id) => {  const rolesMap = {    11: 'ADMIN',    22: 'OPERATOR',    33: 'USER',  }  return rolesMap[id]}

Finally, let's handle the default case of the switch statement by adding a default key:

index.js
const getRole = (id) => {  const defaultKey = 33  const rolesMap = {    11: 'ADMIN',    22: 'OPERATOR',    33: 'USER',  }  return rolesMap[id] ?? rolesMap[defaultKey]}

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.