Basics · beginner
JavaScript Program to Check Leap Year
Check whether a year is a leap year in JavaScript with the full rule (divisible by 4, but centuries only when divisible by 400), and verify it with Date.
- remainder %
- && and ||
- functions
- Date
A leap year has 366 days. A year divisible by 4 is a leap year, except years divisible by 100, which are not, except years divisible by 400, which are. So 2024 and 2000 are leap years, but 1900 and 2100 are not.
Many quick solutions only check the first part and get 1900 wrong. The function below implements all three.
The program
function isLeapYear(year) {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
for (const year of [2024, 2023, 1900, 2000]) {
console.log(year, isLeapYear(year) ? "is a leap year" : "is not a leap year");
}2024 is a leap year
2023 is not a leap year
1900 is not a leap year
2000 is a leap yearHow it works
- year % 4 === 0 keeps only years divisible by 4.
- The part in brackets accepts the year if it is not a century, or if it is a century divisible by 400.
- && needs both sides to be true, so 1900 fails (divisible by 100 but not 400) and 2000 passes.
- The function returns a boolean, and the ternary operator turns it into a sentence.
Watch it run line by line
Each call to isLeapYear opens a new frame with its own year, and the return row shows true or false before the loop prints the sentence.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Ask the Date object
Month 1 is February in JavaScript's Date (months count from 0). Day 29 of February only exists in a leap year; in other years the date rolls over to March 1.
const isLeap = (year) => new Date(year, 1, 29).getDate() === 29;
console.log(isLeap(1900), isLeap(2000), isLeap(2024));false true trueCommon mistakes
- Checking only year % 4 === 0, which makes 1900 and 2100 leap years.
- Forgetting the brackets: && binds tighter than ||, so the condition then means something else.
- Using new Date(year, 2, 29) for February: months start at 0, so 2 is March.
Try it yourself
- Print every leap year between 1890 and 1920.
- Count the leap years from 2000 to 2100 with filter() on an array of years.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.