How to use switch statement In Javascript

In this approach, a switch statement is used to return the number of days based on the specified month. This approach is straightforward and allows for direct mapping of month numbers to the corresponding number of days.

JavaScript
function daysInMonth(month, year) {
    switch (month) {
        case 1: // January
        case 3: // March
        case 5: // May
        case 7: // July
        case 8: // August
        case 10: // October
        case 12: // December
            return 31;
        case 4: // April
        case 6: // June
        case 9: // September
        case 11: // November
            return 30;
        case 2: // February
            return (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 29 : 28;
        default:
            return -1; // Invalid month
    }
}

// Example usage:
let month = 2;
let year = 2024;
console.log("Number of days in " + month + "th month of the year " + year + " is " + daysInMonth(month, year));

Output
Number of days in 2th month of the year 2024 is 29


We have a complete list of Javascript Date Objects, to check those please go through this Javascript Date Object Complete reference article.



How to get the number of days in a specified month using JavaScript ?

Given a month the task is to determine the number of days of that month using JavaScript. we can use the getDate() method for the calculation of number of days in a month.

Similar Reads

JavaScript getDate() Method

getDate() method returns the number of days in a month (from 1 to 31) for the defined date....

2. Using an array to store days in each month

Example 1: Using an array to store days in each month allows for efficient retrieval of the number of days in a specific month based on its index....

3. Using switch statement

In this approach, a switch statement is used to return the number of days based on the specified month. This approach is straightforward and allows for direct mapping of month numbers to the corresponding number of days....