← Back toFront-end tips

Replace multiple if statements with a single switch statement

Written byPhuoc Nguyen
Created
26 Feb, 2021
Category
Trick
Tags
JavaScript
We demonstrate the trick with a simple issue: Determine the quarter of a given date. Since the month in JavaScript is zero-based, the month of a given `date` can be determined as
js
// `date` is the input date
const month = date.getMonth() + 1;
The quarter is calculated based on the range of month:
js
let quarter = 1;
if (month <= 3) {
quarter = 1;
} else if (month <= 6) {
quarter = 2;
} else if (month <= 9) {
quarter = 3;
} else {
quarter = 4;
}
It is not easy for us to scan multiple `if` statements above. We can make it more readable with a single `switch (true)` statement:
js
switch (true) {
case month <= 3:
quarter = 1;
break;
case month <= 6:
quarter = 2;
break;
case month <= 9:
quarter = 3;
break;
default:
quarter = 4;
break;
}
This trick gives us an idea of using `switch (true)` to make the code more readable. The specific issue in this post, calculating the quarter of a given date, can be done with a single line-of-code.

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn