Borislav Hadzhiev
Wed Jan 26 2022·2 min read
Photo by Joshua Fuller
To check if a year is a leap year:
Date
object that stores the 29th of February.function isLeapYear(year = new Date().getFullYear()) { return new Date(year, 1, 29).getDate() === 29; } console.log(isLeapYear(2023)); // 👉️ false console.log(isLeapYear(2024)); // 👉️ true
We created a reusable function that takes a year as a parameter and checks if the year is a leap year.
If no parameters are passed to the function, it uses the current year.
The 3 parameters we passed to the Date() constructor are:
year
- an integer that represents the year.monthIndex
- a zero-based value that represents the month, where 0
is
January, 1
is February, etc.day
- an integer that represents the day of the month.We created a Date
object that stores the date for February 29th.
The
getDate()
method returns a number between 1
and 31
that represents the day of the
month for the given date.
Date
object in JavaScript automatically adjusts the necessary values if passed a greater number.For example, if you pass 29
as the day of the month for a month that only has
28
days, the Date
object would set the date to the first of the next month.
const date = new Date(2022, 1, 29); // 👇️ Tue Mar 01 2022 console.log(date);
We passed 29
for the day of the month when creating the Date
object, but
because the month of February only has 28
days in 2022
, the Date
object
created a date for the 1st of March.
You can also use a more explicit approach.
To check if a year is a leap year:
4
and is not an end-of-century year.400
.function isLeapYear(year = new Date().getFullYear()) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } console.log(isLeapYear(2023)); // 👉️ false console.log(isLeapYear(2400)); // 👉️ true console.log(isLeapYear(2024)); // 👉️ true
For a year to be a leap year, it has to be divisible by 4
, except for
end-of-century years, which must be divisible by 400
.
The modulo (%) operator returns the remainder of the division.
This solution is quite a bit more technical and less readable than the previous one.