Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Switch Statement

Erwin Hom
Erwin Hom
2,070 Points

Is there a better way than to use if/then or switch/case to handle the day of the week (or month name)?

I know you just happen to choose day of the week as your example for the topic.

I believe there are special libraries to getting the name of the month or day of the week.

Wouldn't it be better to use an associative array (hash table, dictionary) instead?

2 Answers

David Bath
David Bath
25,940 Points

I think you're jumping ahead. Has your course gotten to associative arrays yet? This video is trying to teach you how to use a switch statement, so the days of the week is just an example that he used to get the point across.

Steven Parker
Steven Parker
229,785 Points

I agree with David about this just being an example.

But to answer your question, I'd probably do this job with an ordinary array:

var weekdays = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
if (day < 7)
    console.log(weekdays[day]);
else
    console.log("Invalid Day");