Leap Year Check in JavaScript
Divisible by 4, except centuries, except 400. 1900 no. 2000 yes.
BeginnerConditional ProgramsExample 4 of 5
leap-year-check.js
1// Leap year rules:2// 1. Divisible by 4 → Leap year3// 2. BUT if divisible by 100 → NOT leap year4// 3. UNLESS divisible by 400 → Leap year56function isLeapYear(year) {7 if (year % 400 === 0) {8 return true;9 } else if (year % 100 === 0) {10 return false;11 } else if (year % 4 === 0) {12 return true;13 } else {14 return false;15 }16}1718// Test cases19console.log("2000:", isLeapYear(2000) ? "Leap year" : "Not leap year");20console.log("1900:", isLeapYear(1900) ? "Leap year" : "Not leap year");21console.log("2024:", isLeapYear(2024) ? "Leap year" : "Not leap year");22console.log("2023:", isLeapYear(2023) ? "Leap year" : "Not leap year");2324// Method 2: Single expression25function isLeapYear2(year) {26 return (year % 400 === 0) || (year % 4 === 0 && year % 100 !== 0);27}2829console.log("\nUsing single expression:");30console.log("2000:", isLeapYear2(2000));31console.log("1900:", isLeapYear2(1900));32console.log("2024:", isLeapYear2(2024));3334// Method 3: Using ternary35function isLeapYear3(year) {36 return year % 400 === 0 ? true :37 year % 100 === 0 ? false :38 year % 4 === 0 ? true : false;39}4041console.log("\nUsing ternary:");42console.log("2000:", isLeapYear3(2000));43console.log("2023:", isLeapYear3(2023));
Output
2000: Leap year 1900: Not leap year 2024: Leap year 2023: Not leap year Using single expression: 2000: true 1900: false 2024: true Using ternary: 2000: true 2023: false
What's going on
Check % 400 first, then % 100, then % 4. Only % 4 and 1900 becomes a leap year.
2023 is not. If your program says it is, you only tested % 4.