DEV Community

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

Collapse
lucs1590 profile image
Lucas de Brito • 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;
};
Collapse
nas5w profile image
Nick Scialli (he/him) Author

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

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) Author • 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

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

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

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

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