← 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
// `date` is the input date
const month = date.getMonth() + 1;
The quarter is calculated based on the range of month:
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:
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

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

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.