DEV Community

Cover image for Creating a JavaScript Function to Calculate Whether It's a Leap Year

Creating a JavaScript Function to Calculate Whether It's a Leap Year

Nick Scialli (he/him) on April 24, 2020

Calculating whether it's a leap year isn't a straightforward as you might think! Here's how leap years are calculated, as described on Wikipedia: ...
Collapse
 
lucs1590 profile image
Lucas de Brito Silva • Edited

You can do a ternary condition to minimize lines, like this:

function isLeapYear(year) {
    return true ? ((year % 400 === 0) || (year % 100 !== 0)) && ((year % 4) == 0) : false;
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nas5w profile image
Nick Scialli (he/him)

I don't think this will evaluate correctly. Also, long one-liners can feel efficient but they're often pretty hard for others to understand.

Collapse
 
lucs1590 profile image
Lucas de Brito Silva

Really, for those who are not used to it, it is difficult to understand. When I started working with tender conditions I thought "This is very strange!", but I forced myself to learn (even to leave the comfort zone) and now it has become very simple. It's a matter of habit, and believe me, it works perfectly!

Thread Thread
 
nas5w profile image
Nick Scialli (he/him) • Edited

What I'm saying is that your function literally doesn't work correctly.

isLeapYear(2100);
// true

That's incorrect.

Thread Thread
 
lucs1590 profile image
Lucas de Brito Silva

Oh, sorry, you're right! I forget something.
Try again with my changes.

Thread Thread
 
nas5w profile image
Nick Scialli (he/him)

In this case, why do you even need the ternary? true will always evaluate to true.

In other words, this:

true ? ((year % 400 === 0) || (year % 100 !== 0)) && ((year % 4) == 0) : false;

is the exact same thing as this:

((year % 400 === 0) || (year % 100 !== 0)) && ((year % 4) == 0);
Thread Thread
 
lucs1590 profile image
Lucas de Brito Silva

Perfect!!
I totally agree with you! 👏👏👏👏👏👏

Collapse
 
craigewert profile image
CREEE

Very clean. But do the 3 parts in the opposite order.

Assuming you get years randomly, most will be not %4, so handle those first.
Similarly, most %4 years will be not %100, so those are next.

just in case the price of 2 extra "if"s is going to break you.

Collapse
 
upieez profile image
Samuel Huang

I love these short questions and simple explanations! Please do more of these 😁

Collapse
 
generalkorex profile image
Korex

Wow this is straight forward. Thanks for sharing.

Collapse
 
craigewert profile image
CREEE

Clever, but too obscure to save 2 lines of code.

Moreover, using date libs is not cricket. If you have those, I presume you can just ask

Date.isLeapYear(year)

(with some syntax or other)

Collapse
 
thomasbnt profile image
Thomas Bnt

Oh great :o