I am new to Javascript, and have been trying to figure out the best possible equation for a Leap year calculator. I have written the solution like this:
if ((year % 4 ===0 && year % 100 !==0) || (year % 4 ===0 && year % 100 ===0 && year % 400 ===0)) {
alert("Leap");
} else {
alert("Not Leap");
}
After having done that, I googled other ways and found out it could be written like this:
if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 ===0)) {
alert("Leap");
} else {
alert("Not Leap");
}
But I don't understand how it could be written like that, because knowing the conditions for leap years:
I don't understand the logic behind the second code sample, to me, it is as if:
Could someone please explain why the second code sample is also valid, and how it is interpreted?
The condition for a leap year is if the year is divisible by 4 and not by 100, or year is divisible by 400.
Mathematically, anything divisible by 400 is divisible by 4 and by 100, this is the reason why the leap year is if (x % 4 AND NOT x % 100) OR (x % 400).
You can see it like this factor decomposition: 400 = 4 * 100, so any number that may be written as n * 400
may be written as n * 4 * 100
, so your condition is just redundant.