Leap Year Check and Days in a Month
Apply Gregorian leap-year rules and return the exact number of days in any month, including February in leap and common years.
Code
export function isLeapYear(year) {
if (!Number.isInteger(year) || year < 1 || year > 9999) {
throw new RangeError("year must be an integer between 1 and 9999");
}
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
export function daysInMonth(year, month) {
if (!Number.isInteger(month) || month < 1 || month > 12) {
throw new RangeError("month must be an integer between 1 and 12");
}
const lengths = [
31,
isLeapYear(year) ? 29 : 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
];
return lengths[month - 1];
}Inside the snippet
Leap Year Check and Days in a Month comes down to the functions isLeapYear and daysInMonth.
The failure path is explicit — RangeError is raised when the guard condition holds.
Putting it to use
The entry-point signature is export function isLeapYear(year)
Import isLeapYear from the file and call it — the rest of the code is implementation detail.
Core lines
throw new RangeError("year must be an integer between 1 and 9999");
throw new RangeError("month must be an integer between 1 and 12");
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- How does the code behave when input is bad?
- The code throws `RangeError`. Handle it at the call site or let it propagate deliberately.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `isLeapYear`, `daysInMonth` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.