DEV Community

Discussion on: Switch statements in javascript – How to refactor?

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
 
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
 
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
 
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
 
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!