Ever pondered why every four years, we enjoy an extra day? That's the magic of leap years, astronomically aligned to synchronize our calendar with Earth's rotation around the Sun. But how can we implement this in JavaScript? Let's dive in!

The first step is understanding leap years. They are the years that are divisible by 4, but not all years that meet this rule qualify. To determine a leap year in JavaScript, a more specific rule comes into play: a year is a leap year if it is divisible by 4, but not divisible by 100, unless it's also divisible by 400.

Defining Leap Years
Let's write a JavaScript function to determine if a given year is a leap year:

function isLeapYear(year) {
if (year % 4 === 0) {
if (year % 100 !== 0 || year % 400 === 0) {
return true;
}
}
return false;
}
Using the Function

This function takes a year as an argument and returns `true` if the year is a leap year, and `false` otherwise.
Let's check if an input year is a leap year in an interactive way:
const year = prompt("Enter a year:");
alert(`The year ${year} is ${isLeapYear(year) ? '' : 'not '}a leap year.`);

Handle Inputs
When prompting for user input, it's essential to handle invalid inputs, such as non-numeric values or years out of the valid range (1 - 9999).
Here's an-enhanced version of the above script to handle these edge cases:

const year = prompt("Enter a year:");
if (!isNaN(year) && year >= 1 && year <= 9999) {
alert(`The year ${year} is ${isLeapYear(year) ? '' : 'not '}a leap year.`);
} else {
alert("Invalid input! Please enter a year between 1 and 9999.");
}
Next Leap Year




















Another useful function could be finding the next leap year after an input year:
function nextLeapYear(year) {
year++;
while (year <= 9999 && !isLeapYear(year)) {
year++;
}
return year;
}
Predicting the Future
Let's use this function to find the next leap year, assuming we've input '2025' as the current year:
const currentYear = 2025;
console.log(`The next leap year after ${currentYear} is ${nextLeapYear(currentYear)}.`);
And there you have it! We've created simple yet effective functions to handle leap years in JavaScript. Whether you're just curious about when the next one is or need it for a project, these functions should serve you well.