Exercise 20: Check if Year is Leap Year

Problem Statement

Create a function `isLeapYear(year)` that checks if year is leap year. Rules: Divisible by 4, but not by 100 unless also by 400. Example: - isLeapYear(2024) → true - isLeapYear(1900) → false

Sample Output:

isLeapYear(2024) => true
isLeapYear(1900) => false
isLeapYear(2000) => true

Solution

const isLeapYear = (year) => {
  const y = Number(year);
  if (!Number.isInteger(y)) return false;
  return (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0);
};

Explanation

Overall Goal:

  • Leap year check karna (february 29 days).

Line 1: Function header

  • const isLeapYear = (year) => {

Line 2: Convert

  • const y = Number(year);

Line 3: Validation

  • if (!Number.isInteger(y)) return false;

Line 4: Leap year logic

  • return (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0);
  • Divisible by 4, but not 100, unless also 400.

Real world:

  • Date calculations: calendar apps.
  • Form validation: date validation.