Earth doesn’t perfectly orbit the Sun every 365 days. Rather, it irritatingly must make its orbit in oh, I don’t know, roughly 365.242190 days each year.
Due to this inconsiderate behaviour, we must add a leap year into our common calendar known as the Gregorian Calendar.
Like, I presume, many of us, I thought a leap year occurred every four years.
Whether it was a matter of being taught a half-truth from my school teachers many decades ago in School (possible), or simply not paying attention to said teachers (much much more possible), I was wrong on this account.
So, when is a leap year?
According to the very impressively sounding Royal Museum Greenwich, a leaps year must meet the following conditions:
- Any year that is a century (e.g. 2000, 2100, 2400, 1900) must be divisible by 400. So 2000 and, 2400 are leap years but 2100 and, 1900 are not.
- Any other year must be divisible by 4.
Yeap. It’s that first one, I didn’t know about.
So with this in mind, how would we determine if a year is a leap year in JavaScript?
Enter the JavaScript Modulo Operator
To determine if something is divisible by a number we can use the JavaScript modulo operator (%
) to determine the remainder. If the remainder is zero we know it is divisible by a number.
So 12%4
would return 0 because 12 divides perfectly into three lots of four. Whereas 7%3
would have one left over.
Got it? Cool.
The Video
https://youtu.be/-dZb30LpD5I
Releases 17 Sep 2024
The Code
Let’s now create a function called isLeapYear()
that takes a four-digit number for our target year.
Remember our leap years rules.
We need to:
- Check if the year is divisible by 400 (
year%400 == 0
) - Check if the year is divisible by 4 (
year%4 == 0
)
If it is, then: - Check if the year isn’t divisible by 100 (
year%100 != 0
).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// CHECK IF THE TARGET YEAR IS A LEAP YEAR IN JAVASCRIPT function isLeapYear(year){ return year%400 == 0 || (year%4 == 0 && year%100 != 0) } const yearTestArray = [ 2000, 2001, 2100, 2200, 2400, 2024, 2025, 1900, ] const result = yearTestArray.map(year => { return { year, isLeapYear : isLeapYear(year) } }) console.table(result) |
Give it a run to see the results.
1 2 3 4 5 6 7 8 9 10 11 12 |
┌─────────┬──────┬────────────┐ │ (index) │ year │ isLeapYear │ ├─────────┼──────┼────────────┤ │ 0 │ 2000 │ true │ │ 1 │ 2001 │ false │ │ 2 │ 2100 │ false │ │ 3 │ 2200 │ false │ │ 4 │ 2400 │ true │ │ 5 │ 2024 │ true │ │ 6 │ 2025 │ false │ │ 7 │ 1900 │ false │ └─────────┴──────┴────────────┘ |
Why not just use the Date object?
I actually did this in a previous tutorial to get a list of days of the year a particular weekday (e.g. Monday, Tuesday, Wednesday…etc) falls. You can check it out here:
However, I would say that a purely numerical approach is always going to significantly beat a multi-step constructor approach.
Check out this benchmark example:
~Yagi