Leap Year Is Not Every 4 Years

When I was first asked to write function for checking leap year, I instantly answered by writing a function to take the year and divided by four. Wrong.

To begin with, the leap year is not every four years. As to why, there are many answers / discussions out there. But, basically:

A year will be a leap year if it is divisible by 4 but not by 100. If a year is divisible by 4 and by 100, it is not a leap year unless it is also divisible by 400.

Based on that, the JavaScript function to check for leap year look something like:

function isLeapYear(year) {
    return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);

Or an easier way:

function isLeapYear(year) {
    return new Date(year,1,29).getDate() == 29;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s