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.
More
