Replace multiple if statements with a single switch statement
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
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;
}
See also