How to use a switch statement In Javascript

In this approach, we use a switch statement to handle each quarter based on the result of dividing the month number by 3. Each case corresponds to a quarter and we return the appropriate quarter based on the input month.

Example: This example uses switch statement to check the quarter of month.

JavaScript
function getQuarter(month) {
    switch (Math.ceil(month / 3)) {
        case 1:
            return "First Quarter";
        case 2:
            return "Second Quarter";
        case 3:
            return "Third Quarter";
        case 4:
            return "Fourth Quarter";
        default:
            return "Invalid month";
    }
}

console.log(getQuarter(9)); 

Output
Third Quarter

JavaScript: Check the Month is in Which Quarter?

When working with dates in JavaScript, it’s often useful to determine which quarter a particular month falls into. Knowing the quarter can aid in various date-related calculations or visual representations. In this article, we will explore different approaches to check the month and it’s quarter using JavaScript.

These are the following approaches:

Table of Content

  • Using Math operations
  • Using a switch statement

Similar Reads

Using Math operations

In this approach, we divide the month number by 3 and use the Math.ceil() function to round up to the nearest integer. This effectively groups the months into quarters....

Using a switch statement

In this approach, we use a switch statement to handle each quarter based on the result of dividing the month number by 3. Each case corresponds to a quarter and we return the appropriate quarter based on the input month....

Contact Us