How to use an array to store days in each month In Javascript
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.
function daysInMonth(month, year) {
const daysInMonths = [31, (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return daysInMonths[month - 1];
}
// 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
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.