DEV Community

Cover image for Switch statements in javascript – How to refactor?

Switch statements in javascript – How to refactor?

Ajay Kumar Verma on January 30, 2022

The Switch statements are perfectly nice and majorly used in the other traditional language like C, C++, and Java. Why Switch statement? ...
Collapse
 
vbarzana profile image
Victor A. Barzana • Edited

Maybe it would be better to use an array for the days example considering that Su-Sa = 0-6.

const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
console.log(days[new Date().getDay()])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
frankwisniewski profile image
Frank Wisniewski

The day of week was just a example....

console.log( new Date().toLocaleDateString("En-en",{ weekday: 'long' }));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ajayv1 profile image
Ajay Kumar Verma

@frankwisniewski Above was just an example to illustrate how we can acheive the switch statement through JS object.

Thanks for one liner though!

Collapse
 
vbarzana profile image
Victor A. Barzana

Yes sir, I agree with your comment, what I am trying to correct here is about replacing the switch, think of days of the week as fruits, and you will get my point.

Thread Thread
 
frankwisniewski profile image
Frank Wisniewski • Edited

Yes Sir, an array works well for months, days, etc.
The weekday example is not good...

Thread Thread
 
ajayv1 profile image
Ajay Kumar Verma

Updating the code.

Collapse
 
vbarzana profile image
Victor A. Barzana

For example 2, having separate Objects to store the data related to pages is a bit misleading and accessing them by the lowercased output of another property could be buggy and not work as expected, what about storing all data in the same place?

const pageName = document.querySelector('#my-div').dataset.pageName;
const dataPageMapper = {
  homepage: {
        title: 'Home',
        layout: 'index'
  },
 productpage: {
        title: 'Product',
        layout: 'pdp'
  },
  blogpage: {
        title: 'Blog',
        layout: 'blog'
  }
};
const currentPage = dataPageMapper[pageName];
// and be careful with accessing properties of an object that doesn't match your pages config
console.log(currentPage.title + '_' + currentPage.layout);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ajayv1 profile image
Ajay Kumar Verma

Actually, I have taken the more general case when the clubbing is not possible i.e it could be the first object and 2nd object are seperate and coming from different files or place.

for this case though, we could have club the data.

Thanks for the suggestion!

Collapse
 
ajayv1 profile image
Ajay Kumar Verma

Yes Victor, As array is also an object in javascript so it would also work the same. Thanks for the suggestion. I'll update the code.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Example 1 would be simpler with an array.

Also, you can add js after the opening backticks on the code blocks to switch on syntax highlighting

Collapse
 
ajayv1 profile image
Ajay Kumar Verma

Yes @jonrandy As array is also an object in javascript so it would also work the same. Thanks for the suggestion.

Collapse
 
jwhenry3 profile image
Justin Henry

I like to use the object map pattern to avoid switch statements, as it does allow adding keys and values to increase the flexibility of the condition, and allows direct access to map values rather than relying on logic branches (which could cause complexity issues for grading platforms). Another thought is parallel arrays, but that requires a little more care when constructing as you will need to know what each index means in the parallel arrays. being able to access map[key].property to avoid branches are really nice.

Collapse
 
ajayv1 profile image
Ajay Kumar Verma

Yes Justin, I also do the same and thought of sharing this point through the article. I am new to dev.to, Its really nice to share and get the comments.

Collapse
 
lexlohr profile image
Alex Lohr

Switch statements can shine if multiple comparators should yield the same result. Otherwise objects, Maps (if the comparators are not strings) or if/else/ternary chains are better.

Collapse
 
ajayv1 profile image
Ajay Kumar Verma

Alex, didn't get the point.

You mean if comparators are string then switch would be better? I don't think so, as matching the string the object key will take same amount of time same as switch.

Collapse
 
lexlohr profile image
Alex Lohr

Maybe an oversimplified example may help:

const positionInWeek = (dayOfWeek) => {
  switch (dayOfWeek) {
    case "Monday":
    case "Tuesday":
      return "Start of the week"
    case "Wednesday":
    case "Thursday":
    case "Friday":
      return "Middle of the week"
    case "Saturday":
    case "Sunday":
      return "End of the week"
    default:
      throw new Error("Not a week day")
  }
}
Enter fullscreen mode Exit fullscreen mode

This would be harder to understand in an object or if-else-if-chain.