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.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
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

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.