DEV Community

Cover image for JavaScript Dev Learning Journey - Leap Year!
Sam
Sam

Posted on

JavaScript Dev Learning Journey - Leap Year!

I am currently picking back up on assignments I have been working on to improve my JavaScript self-learning journey and currently doing a program to determine if a year given is a Leap Year or not! What better way to start a new year :-)

My first step right away was looking up the method of how to determine if a year is a leap year, which I found out through a Microsoft docs which states the following:

Any year that is evenly divisible by 4 is a leap year: for example, 1988, 1992, and 1996 are leap years.

Which seems pretty easy ! Right away I knew I would be coding a conditional statement so I wrote up the following:

const leapYears = function (yearNum) {

    if (yearNum % 4 == 0) {
        return true;
    }else{
        return false;
    }

};

Enter fullscreen mode Exit fullscreen mode

Of course, as I was going through the tests, thinking I am in the clear, I knew a part of me felt that this was too easy/good to be true. Sure enough, I ran into a problem where my test failed when the year was 1900 for example. So what I decided to do was go back to documentation to see if there's anything about that and sure enough:

However, there is still a small error that must be accounted for. To eliminate this error, the Gregorian calendar stipulates that a year that is evenly divisible by 100 (for example, 1900) is a leap year only if it is also evenly divisible by 400.

So that means although 1900 works with 100, it doesn't work with 400 and therefore is not a leap year!

So, now I need to account for how to make a number go through several checks:

  1. Make sure it is divisible by 4.
  2. Check to see if it's divisible by 100 AND 400 after checking if divisible by 4.
  3. If it's divisible by 100 but NOT 400, it's not a leap year. Same if it's flipped around.

That's a simple fix! Taking my previous code, I've updated it to the following:

const leapYears = function (yearNum) {

    if (yearNum % 4 == 0 && yearNum % 100 == 0 && yearNum % 400 == 0) {
        return true;
    }else{
        return false;
    }

    //Any year divisible by 4 is a leap year.
    //Check if divisible by 3 numbers: 4, 100, and 400. 
    //if-statements on passing all three conditions to be leap years


};

Enter fullscreen mode Exit fullscreen mode

Where yearNum is checked to have a remainder 0(hence the usage of % to show if it's divisible by a number) with 4, 100, AND 400. This will cover the cases where it can be divisible by 4 and 100 BUT not by 400, making it NOT a leap year. This goes the same if divisible by 100 and 400, but not 4 in addition to divisible by 400 and 4, but not 100.

And no-- 2022 is not a leap year. 2024 is when we will have our next leap year!

Top comments (0)